1 /*
   2  * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.oracle.tools.packager;
  27 
  28 import com.oracle.tools.packager.Log;
  29 import java.io.*;
  30 import java.net.URL;
  31 import java.nio.channels.FileChannel;
  32 import java.util.Arrays;
  33 
  34 public class IOUtils {
  35 
  36     public static boolean deleteRecursive(File path) throws FileNotFoundException {
  37         boolean ret = true;
  38         if (!path.exists()) { //nothing to do
  39             return true;
  40         }
  41         if (path.isDirectory()) {
  42             File[] children = path.listFiles();
  43             if (children != null) {
  44                 for (File f : children) {
  45                     ret = ret && deleteRecursive(f);
  46                 }
  47             }
  48         }
  49         return ret && path.delete();
  50     }
  51 
  52     public static void copyFromURL(URL location, File file) throws IOException {
  53         if (location == null) {
  54             throw new IOException("Missing input resource!");
  55         }
  56         if (file.exists()) {
  57            file.delete();
  58         }
  59         InputStream in = location.openStream();
  60         FileOutputStream out = new FileOutputStream(file);
  61         byte[] buffer = new byte[1024];
  62         int len;
  63         while ((len = in.read(buffer)) != -1) {
  64             out.write(buffer, 0, len);
  65         }
  66         out.close();
  67         in.close();
  68         file.setReadOnly();
  69         file.setReadable(true, false);
  70     }
  71 
  72     public static void copyFile(File sourceFile, File destFile)
  73             throws IOException {
  74         destFile.getParentFile().mkdirs();
  75 
  76         //recreate the file as existing copy may have weird permissions
  77         destFile.delete();
  78         destFile.createNewFile();
  79 
  80         FileChannel source = null;
  81         FileChannel destination = null;
  82         source = new FileInputStream(sourceFile).getChannel();
  83         destination = new FileOutputStream(destFile).getChannel();
  84         if (destination != null && source != null) {
  85             destination.transferFrom(source, 0, source.size());
  86         }
  87         if (source != null) {
  88             source.close();
  89         }
  90         if (destination != null) {
  91             destination.close();
  92         }
  93 
  94         //preserve executable bit!
  95         if (sourceFile.canExecute()) {
  96             destFile.setExecutable(true, false);
  97         }
  98         if (!sourceFile.canWrite()) {
  99             destFile.setReadOnly();
 100         }
 101         destFile.setReadable(true, false);
 102     }
 103 
 104     public static long getFolderSize(File folder) {
 105         long foldersize = 0;
 106 
 107         File[] children = folder.listFiles();
 108         if (children != null) {
 109             for (File f : children) {
 110                 if (f.isDirectory()) {
 111                     foldersize += getFolderSize(f);
 112                 } else {
 113                     foldersize += f.length();
 114                 }
 115             }
 116         }
 117 
 118         return foldersize;
 119     }
 120 
 121     //run "launcher paramfile" in the directory where paramfile is kept
 122     public static void run(String launcher, File paramFile, boolean verbose)
 123             throws IOException {
 124         if (paramFile != null && paramFile.exists()) {
 125             ProcessBuilder pb = new ProcessBuilder(launcher, paramFile.getName());
 126             pb = pb.directory(paramFile.getParentFile());
 127             exec(pb, verbose);
 128         }
 129     }
 130 
 131     public static void exec(ProcessBuilder pb, boolean verbose) throws IOException {
 132         exec(pb, verbose, false);
 133     }
 134 
 135 
 136     public static void exec(ProcessBuilder pb, boolean verbose,
 137             boolean testForPresenseOnly) throws IOException {
 138         exec(pb, verbose, testForPresenseOnly, null);
 139     }
 140 
 141     public static void exec(ProcessBuilder pb, boolean verbose,
 142             boolean testForPresenseOnly, PrintStream consumer) throws IOException {
 143         pb.redirectErrorStream(true);
 144         Log.verbose("Running " + Arrays.toString(pb.command().toArray(new String[0]))
 145                                 + (pb.directory() != null ? (" in " + pb.directory()) : ""));
 146         Process p = pb.start();
 147         InputStreamReader isr = new InputStreamReader(p.getInputStream());
 148         BufferedReader br = new BufferedReader(isr);
 149         String lineRead;
 150         while ((lineRead = br.readLine()) != null) {
 151             if (consumer != null) {
 152                 consumer.print(lineRead);
 153             } else if (verbose) {
 154                Log.info(lineRead);
 155             } else {
 156                Log.debug(lineRead);
 157             }
 158         }
 159         try {
 160             int ret = p.waitFor();
 161             if (ret != 0 && !(testForPresenseOnly && ret != 127)) {
 162                 throw new IOException("Exec failed with code " + ret +
 163                         " command [" + Arrays.toString(pb.command().toArray(new String[0])) +
 164                         " in " + (pb.directory() != null ?
 165                            pb.directory().getAbsolutePath() : "unspecified directory"));
 166             }
 167         } catch (InterruptedException ex) {
 168         }
 169     }
 170 
 171     //no good test if we are running pre-JRE7
 172     //use heuristic approach
 173     // "false positive" is better than wrong answer
 174     public static boolean isNotSymbolicLink(File file) {
 175         //no symlinks on windows
 176         if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
 177             return true;
 178         }
 179         try {
 180             if (file == null || file.getParent() == null) {
 181                 return false;
 182             }
 183             File file_canonical = new File(
 184                     file.getParentFile().getCanonicalFile(), file.getName());
 185             if (file_canonical.getCanonicalFile().equals(
 186                        file_canonical.getAbsoluteFile())) {
 187                 return true;
 188             }
 189         } catch (IOException ioe) {}
 190         return false;
 191     }
 192 
 193     public static byte[] readFully(File f) throws IOException {
 194         InputStream inp = new FileInputStream(f);
 195         //read fully into memory
 196         ByteArrayOutputStream baos = new ByteArrayOutputStream();
 197         byte[] buffer = new byte[1024];
 198         int length = 0;
 199         while ((length = inp.read(buffer)) != -1) {
 200             baos.write(buffer, 0, length);
 201         }
 202         baos.close();
 203         return baos.toByteArray();
 204     }
 205 }