1 /*
   2  * Copyright (c) 2012, 2016, 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         copyFromURL(location, file, false);
  54     }
  55 
  56     public static void copyFromURL(URL location, File file, boolean append) throws IOException {
  57         if (location == null) {
  58             throw new IOException("Missing input resource!");
  59         }
  60         if (file.exists() && !append) {
  61            file.delete();
  62         }
  63         InputStream in = location.openStream();
  64         FileOutputStream out = new FileOutputStream(file, append);
  65         byte[] buffer = new byte[1024];
  66         int len;
  67         while ((len = in.read(buffer)) != -1) {
  68             out.write(buffer, 0, len);
  69         }
  70         out.close();
  71         in.close();
  72         file.setReadOnly();
  73         file.setReadable(true, false);
  74     }
  75 
  76     public static void copyFile(File sourceFile, File destFile)
  77             throws IOException {
  78         destFile.getParentFile().mkdirs();
  79 
  80         //recreate the file as existing copy may have weird permissions
  81         destFile.delete();
  82         destFile.createNewFile();
  83 
  84         FileChannel source = null;
  85         FileChannel destination = null;
  86         source = new FileInputStream(sourceFile).getChannel();
  87         destination = new FileOutputStream(destFile).getChannel();
  88         if (destination != null && source != null) {
  89             destination.transferFrom(source, 0, source.size());
  90         }
  91         if (source != null) {
  92             source.close();
  93         }
  94         if (destination != null) {
  95             destination.close();
  96         }
  97 
  98         //preserve executable bit!
  99         if (sourceFile.canExecute()) {
 100             destFile.setExecutable(true, false);
 101         }
 102         if (!sourceFile.canWrite()) {
 103             destFile.setReadOnly();
 104         }
 105         destFile.setReadable(true, false);
 106     }
 107 
 108     public static long getFolderSize(File folder) {
 109         long foldersize = 0;
 110 
 111         File[] children = folder.listFiles();
 112         if (children != null) {
 113             for (File f : children) {
 114                 if (f.isDirectory()) {
 115                     foldersize += getFolderSize(f);
 116                 } else {
 117                     foldersize += f.length();
 118                 }
 119             }
 120         }
 121 
 122         return foldersize;
 123     }
 124 
 125     //run "launcher paramfile" in the directory where paramfile is kept
 126     public static void run(String launcher, File paramFile, boolean verbose)
 127             throws IOException {
 128         if (paramFile != null && paramFile.exists()) {
 129             ProcessBuilder pb = new ProcessBuilder(launcher, paramFile.getName());
 130             pb = pb.directory(paramFile.getParentFile());
 131             exec(pb, verbose);
 132         }
 133     }
 134 
 135     public static void exec(ProcessBuilder pb, boolean verbose) throws IOException {
 136         exec(pb, verbose, false);
 137     }
 138 
 139 
 140     public static void exec(ProcessBuilder pb, boolean verbose,
 141             boolean testForPresenseOnly) throws IOException {
 142         exec(pb, verbose, testForPresenseOnly, null);
 143     }
 144 
 145     public static void exec(ProcessBuilder pb, boolean verbose,
 146             boolean testForPresenseOnly, PrintStream consumer) throws IOException {
 147         pb.redirectErrorStream(true);
 148         Log.verbose("Running " + Arrays.toString(pb.command().toArray(new String[0]))
 149                                 + (pb.directory() != null ? (" in " + pb.directory()) : ""));
 150         Process p = pb.start();
 151         InputStreamReader isr = new InputStreamReader(p.getInputStream());
 152         BufferedReader br = new BufferedReader(isr);
 153         String lineRead;
 154         while ((lineRead = br.readLine()) != null) {
 155             if (consumer != null) {
 156                 consumer.print(lineRead + '\n');
 157             } else if (verbose) {
 158                Log.info(lineRead);
 159             } else {
 160                Log.debug(lineRead);
 161             }
 162         }
 163         try {
 164             int ret = p.waitFor();
 165             if (ret != 0 && !(testForPresenseOnly && ret != 127)) {
 166                 throw new IOException("Exec failed with code " + ret +
 167                         " command [" + Arrays.toString(pb.command().toArray(new String[0])) +
 168                         " in " + (pb.directory() != null ?
 169                            pb.directory().getAbsolutePath() : "unspecified directory"));
 170             }
 171         } catch (InterruptedException ex) {
 172         }
 173     }
 174 
 175     //no good test if we are running pre-JRE7
 176     //use heuristic approach
 177     // "false positive" is better than wrong answer
 178     public static boolean isNotSymbolicLink(File file) {
 179         //no symlinks on windows
 180         if (Platform.getPlatform() == Platform.WINDOWS) {
 181             return true;
 182         }
 183         try {
 184             if (file == null || file.getParent() == null) {
 185                 return false;
 186             }
 187             File file_canonical = new File(
 188                     file.getParentFile().getCanonicalFile(), file.getName());
 189             if (file_canonical.getCanonicalFile().equals(
 190                        file_canonical.getAbsoluteFile())) {
 191                 return true;
 192             }
 193         } catch (IOException ioe) {}
 194         return false;
 195     }
 196 
 197     public static byte[] readFully(File f) throws IOException {
 198         InputStream inp = new FileInputStream(f);
 199         //read fully into memory
 200         ByteArrayOutputStream baos = new ByteArrayOutputStream();
 201         byte[] buffer = new byte[1024];
 202         int length = 0;
 203         while ((length = inp.read(buffer)) != -1) {
 204             baos.write(buffer, 0, length);
 205         }
 206         baos.close();
 207         return baos.toByteArray();
 208     }
 209 }