1 15 package org.apache.hivemind.build; 16 17 import java.io.BufferedOutputStream ; 18 import java.io.File ; 19 import java.io.FileOutputStream ; 20 import java.io.IOException ; 21 import java.io.InputStream ; 22 import java.io.OutputStream ; 23 import java.net.URL ; 24 import java.net.URLConnection ; 25 26 import org.apache.tools.ant.BuildException; 27 import org.apache.tools.ant.Project; 28 import org.apache.tools.ant.Task; 29 30 42 public class Grabber extends Task 43 { 44 private URL _src; 45 46 private File _dest; 47 48 public void execute() throws BuildException 49 { 50 if (_src == null) 51 throw new BuildException("src is required", getLocation()); 52 53 if (_dest == null) 54 throw new BuildException("dest is required", getLocation()); 55 56 if (_dest.exists()) 57 { 58 59 if (_dest.isDirectory()) 60 throw new BuildException("The specified destination is a directory", getLocation()); 61 62 if (isNonZeroLength(_dest)) 63 return; 64 65 if (!_dest.canWrite()) 66 throw new BuildException("Can't write to " + _dest.getAbsolutePath(), getLocation()); 67 } 68 69 try 70 { 71 72 URLConnection connection = _src.openConnection(); 73 74 connection.connect(); 75 76 copyConnectionToFile(connection); 77 } 78 catch (IOException ex) 79 { 80 log("Failure accessing " + _src + ": " + ex.getMessage(), Project.MSG_ERR); 81 } 82 } 83 84 private boolean isNonZeroLength(File file) 85 { 86 return file.length() > 0; 87 } 88 89 private void copyConnectionToFile(URLConnection connection) throws IOException 90 { 91 log("Downloading " + _src + " to " + _dest); 92 93 InputStream is = open(connection); 94 95 FileOutputStream fos = new FileOutputStream (_dest); 96 OutputStream os = new BufferedOutputStream (fos); 97 98 byte[] buffer = new byte[100 * 1024]; 99 100 while (true) 101 { 102 int bytesRead = is.read(buffer); 103 104 if (bytesRead < 0) 105 break; 106 107 os.write(buffer, 0, bytesRead); 108 } 109 110 is.close(); 111 os.close(); 112 } 113 114 private InputStream open(URLConnection connection) 115 { 116 InputStream result = null; 117 118 int i = 0; 119 while (true) 120 { 121 try 122 { 123 result = connection.getInputStream(); 124 break; 125 } 126 catch (IOException ex) 127 { 128 if (i++ == 3) 129 throw new BuildException("Unable to open " + _src + ": " + ex.getMessage(), ex, 130 getLocation()); 131 } 132 } 133 134 if (result == null) 135 throw new BuildException("Unable to open " + _src, getLocation()); 136 137 return result; 138 } 139 140 public void setDest(File file) 141 { 142 _dest = file; 143 } 144 145 public void setSrc(URL url) 146 { 147 _src = url; 148 } 149 150 } | Popular Tags |