| [ Index ] |
PHP Cross Reference of Drupal 6 (yi-drupal) |
[Summary view] [Print] [Text view]
1 /* Copyright (C) 2005 Simon David Rycroft 2 3 This program is free software; you can redistribute it and/or 4 modify it under the terms of the GNU General Public License 5 as published by the Free Software Foundation; either version 2 6 of the License, or (at your option) any later version. 7 8 This program is distributed in the hope that it will be useful, 9 but WITHOUT ANY WARRANTY; without even the implied warranty of 10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 GNU General Public License for more details. 12 13 You should have received a copy of the GNU General Public License 14 along with this program; if not, write to the Free Software 15 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ 16 17 import com.sun.java.browser.net.ProxyInfo; 18 import com.sun.java.browser.net.ProxyService; 19 import java.io.File; 20 import java.io.FileInputStream; 21 import java.io.BufferedOutputStream; 22 import java.io.DataOutputStream; 23 import java.io.InputStreamReader; 24 import java.io.BufferedReader; 25 import java.net.Socket; 26 import java.net.URL; 27 import java.util.Random; 28 import javax.net.ssl.TrustManager; 29 import javax.net.ssl.X509TrustManager; 30 import javax.net.ssl.SSLContext; 31 32 import java.net.UnknownHostException; 33 import java.io.IOException; 34 import java.io.FileNotFoundException; 35 import java.io.UnsupportedEncodingException; 36 37 import java.io.InputStream; 38 import java.awt.image.BufferedImage; 39 import javax.imageio.ImageIO; 40 import java.awt.Graphics2D; 41 import java.awt.RenderingHints; 42 import java.io.ByteArrayOutputStream; 43 import java.io.ByteArrayInputStream; 44 45 public class UploadThread extends Thread{ 46 47 private File file; 48 private Main main; 49 private int attempts, finalByteSize; 50 private static final String lotsHyphens="---------------------------"; 51 private static final String lineEnd="\r\n"; 52 private String header, footer, request, reply, afterContent; 53 private InputStream fileStream; 54 private URL url; 55 private String boundary; 56 private Socket sock; 57 private boolean addPngToFileName; 58 private boolean doUpload; 59 private String fileuploadname; 60 61 public UploadThread(URL u, File f, Main m) throws IOException, UnknownHostException{ 62 63 url = u; 64 file = f; 65 main = m; 66 attempts = 0; 67 doUpload = true; 68 69 try { 70 fileuploadname = main.getParameter("fileuploadname"); 71 if (fileuploadname.equals("") || fileuploadname.equals(null)) 72 fileuploadname = "s_filename"; 73 } catch (NullPointerException ex_fileuploadname){ 74 // Default language being set 75 fileuploadname = "s_filename"; 76 } 77 } 78 79 public void run(){ 80 try { 81 upload(); 82 } 83 catch (FileNotFoundException fnfe) { 84 // A file has been moved or deleted. This file will NOT 85 // be uploaded. 86 // Set the progress to include this file. 87 main.fileNotFound(file); 88 main.setProgress((int)file.length()); 89 } 90 catch (IOException ioe){ 91 // No idea what could have caused this, so simply call this.run() again. 92 this.run(); 93 // This could end up looping. Probably need to find out what could cause this. 94 // I guess I could count the number of attempts! 95 main.errorMessage("IOException: UploadThread"); 96 } 97 } 98 99 public void cancelUpload(){ 100 doUpload = false; 101 } 102 private void upload() throws FileNotFoundException, IOException{ 103 104 this.uploadFile(); 105 // Check to see if the file was uploaded 106 if (reply != null && reply.indexOf("POSTLET:NO")>0) { 107 if (reply.indexOf("POSTLET:RETRY")>0){ 108 reply = ""; 109 if (attempts<3) { 110 main.setProgress(-(int)file.length()); 111 main.setProgress(finalByteSize); // Has to be added after whole file is removed. 112 attempts++; 113 this.upload(); 114 } 115 else { 116 main.fileUploadFailed(file); 117 main.setProgress(finalByteSize); 118 } 119 } else { 120 if(reply.indexOf("POSTLET:FILE TYPE NOT ALLOWED")>0){ 121 main.fileNotAllowed(file); 122 } 123 else { 124 main.fileUploadFailed(file); 125 } 126 attempts = 5; 127 main.setProgress(finalByteSize); 128 } 129 } 130 else { 131 // Set the progress, that this file has uploaded. 132 main.addUploadedFile(file); 133 main.setProgress(finalByteSize); 134 } 135 } 136 137 private synchronized void uploadFile() throws FileNotFoundException, IOException{ 138 139 // Get the file stream first, as this is needed for the content-length 140 // header. 141 this.setInputStream(); 142 143 sock = getSocket(); 144 145 this.setBoundary(40); 146 this.setHeaderAndFooter(); 147 // Output stream, for writing to the socket. 148 DataOutputStream output = new DataOutputStream(new BufferedOutputStream(sock.getOutputStream())); 149 // Reader for accepting the reply from the server. 150 BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream())); 151 152 // Write the request, and the header. 153 output.writeBytes(request); 154 try { 155 output.write(header.getBytes("UTF-8")); }// Write in UTF-8! - May change all 156 catch (UnsupportedEncodingException uee){ 157 // Just ignore this error, and instead write out the bytes without 158 // getting as UTF-8! 159 main.errorMessage("Couldn't get header in UTF-8"); 160 output.writeBytes(header); 161 } 162 163 output.flush(); 164 165 // Create a ReadLine thread to read the possible output. 166 // Possible catching of errors here if the return isn't 100 continue 167 ReadLine rl = new ReadLine(input, this); 168 rl.start(); 169 try { 170 // Should be dynamically setting this. 171 wait(1000); 172 } 173 catch (InterruptedException ie){ 174 // Thread was interuppted, which means there was probably 175 // some output! 176 } 177 output.writeBytes(afterContent); 178 // Debug: Show that the above has passed! 179 180 // Following reads the file, and streams it. 181 ///////////////////////////////////////////////////////////// 182 //FileInputStream fileStream = new FileInputStream(file); 183 int numBytes = 0; 184 185 if (file.length()>Integer.MAX_VALUE){ 186 throw new IOException("*** FILE TOO BIG ***"); 187 } 188 189 // Size of buffer - May need reducing if users encounter 190 // memory issues. 191 int maxBufferSize = 1024; 192 int bytesAvailable = fileStream.available(); 193 int bufferSize = Math.min(bytesAvailable,maxBufferSize); 194 finalByteSize = 0; // Needs to be passed to the upload method! 195 196 byte buffer [] = new byte[bufferSize]; 197 198 int bytesRead = fileStream.read(buffer, 0, bufferSize); 199 while (bytesAvailable > 0 && doUpload) 200 { 201 output.write(buffer, 0, bufferSize); 202 if (bufferSize == maxBufferSize) 203 main.setProgress(bufferSize); 204 else 205 finalByteSize = bufferSize; 206 bytesAvailable = fileStream.available(); 207 bufferSize = Math.min(bytesAvailable,maxBufferSize); 208 bytesRead = fileStream.read(buffer, 0, bufferSize); 209 } 210 /////////////////////////////////////////////////////////// 211 if (doUpload){ 212 output.writeBytes(footer); 213 output.writeBytes(lineEnd); 214 215 output.flush(); 216 217 try { 218 // Should be dynamically setting this. 219 wait(1000); 220 } 221 catch (InterruptedException ie){ 222 // Thread was interuppted, which means there was probably 223 // some output! 224 } 225 reply = rl.getRead(); 226 main.errorMessage("REPLY"); 227 main.errorMessage(reply); 228 main.errorMessage("END REPLY"); 229 } 230 // Close the socket and streams. 231 input.close(); 232 output.close(); 233 sock.close(); 234 } 235 236 // Each UploadThread gets a new Socket. 237 // This is bad, especially when talking to HTTP/1.1 servers 238 // which are able to keep a connection alive. May change this 239 // to have the UploadManager create the threads, and reuse them 240 // passing them to each of the UploadThreads. 241 private Socket getSocket() throws IOException, UnknownHostException{ 242 if (url.getProtocol().equalsIgnoreCase("https")){ 243 // Create a trust manager that does not validate certificate chains 244 TrustManager[] trustAllCerts = new TrustManager[]{ 245 new X509TrustManager() { 246 public java.security.cert.X509Certificate[] getAcceptedIssuers() { 247 return null; 248 } 249 public void checkClientTrusted( 250 java.security.cert.X509Certificate[] certs, String authType) { 251 } 252 public void checkServerTrusted( 253 java.security.cert.X509Certificate[] certs, String authType) { 254 } 255 } 256 }; 257 // Install the all-trusting trust manager 258 try { 259 SSLContext sc = SSLContext.getInstance("SSL"); 260 sc.init(null, trustAllCerts, new java.security.SecureRandom()); 261 int port = url.getPort(); 262 if (url.getPort()>0) 263 return sc.getSocketFactory().createSocket(url.getHost(),url.getPort()); 264 else 265 return sc.getSocketFactory().createSocket(url.getHost(),443); 266 } 267 catch (Exception e) { 268 } 269 } 270 else { 271 try { 272 ProxyInfo info[] = ProxyService.getProxyInfo(url); 273 if(info != null && info.length>0){ 274 String proxyHost = info[0].getHost(); 275 int proxyPort = info[0].getPort(); 276 main.errorMessage("PROXY = " + proxyHost + ":" + proxyPort); 277 return new Socket(proxyHost, proxyPort); 278 } 279 }catch (Exception ex) { 280 main.errorMessage("could not retrieve proxy configuration, attempting direct connection."); 281 } 282 Socket s; 283 String proxyHost = System.getProperties().getProperty("deployment.proxy.http.host"); 284 String proxyPort = System.getProperties().getProperty("deployment.proxy.http.port"); 285 String proxyType = System.getProperties().getProperty("deployment.proxy.type"); 286 if ( (proxyHost == null || proxyType == null) || (proxyHost.equalsIgnoreCase("") || proxyType.equalsIgnoreCase("0") || proxyType.equalsIgnoreCase("2") || proxyType.equalsIgnoreCase("-1") )){ 287 if(!main.getProxy().equals("")){ 288 String proxyParts[] = main.getProxy().split(":"); 289 try{ 290 s = new Socket(proxyParts[0],Integer.parseInt(proxyParts[1])); 291 main.errorMessage("Proxy (parameter) - "+proxyParts[0]+":"+proxyParts[1]); 292 } 293 catch (NumberFormatException badPort){ 294 main.errorMessage("bad proxy parameter"); 295 if (url.getPort()>0) 296 s = new Socket(url.getHost(),url.getPort()); 297 else 298 s = new Socket(url.getHost(),80); 299 } 300 } 301 if (url.getPort()>0) 302 s = new Socket(url.getHost(),url.getPort()); 303 else 304 s = new Socket(url.getHost(),80); 305 } 306 else{ 307 // Show when a Proxy is being user. 308 main.errorMessage("Proxy (browser) - "+proxyHost+" - "+proxyPort+" - "+proxyType); 309 try { 310 s = new Socket(proxyHost,Integer.parseInt(proxyPort));} 311 catch (NumberFormatException badPort){ 312 // Probably not a bad idea to try a list of standard Proxy ports 313 // here (8080, 3128 ..), then default to trying the final one. 314 // This could possibly be causing problems, display of an 315 // error message is probably also a good idea. 316 main.errorMessage("bad proxy from browser"); 317 if (url.getPort()>0) 318 s = new Socket(url.getHost(),url.getPort()); 319 else 320 s = new Socket(url.getHost(),80); 321 } 322 } 323 return s; 324 } 325 return null;// Add an error here! 326 } 327 328 private void setInputStream() throws FileNotFoundException{ 329 //check if the file is an image from its extention 330 String fileExt = file.getName(); 331 fileExt=fileExt.substring(fileExt.lastIndexOf(".")+1); 332 333 // If file is an image supported by Java (Currently only JPEG, GIF and PNG) 334 if((fileExt.equalsIgnoreCase("gif") 335 ||fileExt.equalsIgnoreCase("jpg") 336 ||fileExt.equalsIgnoreCase("jpeg") 337 ||fileExt.equalsIgnoreCase("png")) && main.getMaxPixels()>0){ 338 try { 339 BufferedImage buf=ImageIO.read(file); 340 int currentPixels = buf.getWidth()*buf.getHeight(); 341 int maxPixels = main.getMaxPixels(); 342 if (currentPixels>maxPixels){ 343 double reduceBy = Math.sqrt(maxPixels)/Math.sqrt(currentPixels); 344 int newWidth=(int)Math.round(buf.getWidth()*reduceBy); 345 int newHeigth=(int)Math.round(buf.getHeight()*reduceBy); 346 BufferedImage bufFinal=new BufferedImage(newWidth,newHeigth,BufferedImage.TYPE_INT_RGB); 347 Graphics2D g=(Graphics2D)bufFinal.getGraphics(); 348 g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR); 349 g.drawImage(buf,0,0,newWidth,newHeigth,null); 350 g.dispose(); 351 ByteArrayOutputStream baos=new ByteArrayOutputStream(); 352 if (fileExt.equalsIgnoreCase("jpg")||fileExt.equalsIgnoreCase("jpeg")) 353 ImageIO.write(bufFinal,"JPG",baos); 354 else {// Note, GIF is converted to PNG, we need to change the filename 355 ImageIO.write(bufFinal,"PNG",baos); 356 if (fileExt.equalsIgnoreCase("gif")){ 357 // File is a gif, hence, add png to the filename 358 addPngToFileName = true; 359 } 360 } 361 362 // Set the progress to increase by the amount that the image 363 // is reduced in size 364 main.setProgress((int)file.length()-baos.size()); 365 fileStream = new ByteArrayInputStream(baos.toByteArray()); 366 } 367 else{ 368 //if image don't need resize 369 fileStream = new FileInputStream(file); 370 } 371 } 372 catch (IOException e){ 373 // Error somewhere 374 fileStream = new FileInputStream(file); 375 } 376 } 377 else{ 378 //if the file is not an image, or maxPixels is not set 379 fileStream = new FileInputStream(file); 380 } 381 } 382 383 private void setBoundary(int length){ 384 385 char [] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; 386 Random r = new Random(); 387 String boundaryString =""; 388 for (int i=0; i< length; i++) 389 boundaryString += alphabet[r.nextInt(alphabet.length)]; 390 boundary = boundaryString; 391 } 392 393 private void setHeaderAndFooter() throws IOException{ 394 395 header = new String(); 396 footer = new String(); 397 request = new String(); 398 399 // AfterContent is what is sent after the Content-Length header field, 400 // but before the file itself. The length of this, is what is required 401 // by the content-length header (along with the length of the file). 402 403 afterContent = lotsHyphens +"--"+ boundary + lineEnd + 404 "Content-Disposition: form-data; name=\"" + fileuploadname + "\"; filename=\""+file.getName(); 405 if (addPngToFileName) 406 afterContent += ".png"; 407 afterContent += "\""+lineEnd+ 408 "Content-Type: application/octet-stream"+lineEnd+lineEnd; 409 410 //footer = lineEnd + lineEnd + "--"+ lotsHyphens+boundary+"--"; 411 // LineEnd removed as it was adding an extra byte to the uploaded file 412 footer = lineEnd + "--"+ lotsHyphens+boundary+"--" + lineEnd; 413 414 // The request includes the absolute URI to the script which will 415 // accept the file upload. This is perfectly valid, although it is 416 // normally only used by a client when connecting to a proxy server. 417 // COULD CREATE PROBLEMS WITH SOME WEB SERVERS. 418 request="POST " + url.toExternalForm() + " HTTP/1.1" + lineEnd; 419 420 // Host that we are sending to (not necesarily connecting to, if behind 421 // a proxy) 422 header +="Host: " + url.getHost() + lineEnd; 423 424 // Give a user agent just for completeness. This could be changed so that 425 // access by the Postlet applet can be logged. 426 //header +="User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.10)" + lineEnd; 427 //Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.8) 428 header +="User-Agent: Mozilla/5.0 (Java/Postlet; rv:" + main.postletVersion + ")" + lineEnd; 429 430 431 // Expect a 100-Continue message 432 // header +="Expect: 100-continue" + lineEnd; 433 434 // Standard accept 435 header +="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"+ lineEnd; 436 header +="Accept-Language: en-us,en;q=0.5" + lineEnd; 437 header +="Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7" + lineEnd; 438 439 // Add the cookie if it is set in the browser 440 String cookie = main.getCookie(); 441 if (cookie.length()>0){ 442 header +="Cookie: "+cookie+lineEnd; 443 } 444 445 header +="Connection: close" + lineEnd; 446 447 // What we are sending. 448 header +="Content-Type: multipart/form-data; boundary=" + lotsHyphens + boundary + lineEnd; 449 450 // Length of what we are sending. 451 header +="Content-Length: "; 452 header += ""+(fileStream.available()+afterContent.length()+footer.length())+lineEnd+lineEnd; 453 } 454 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated: Mon Jul 9 18:01:44 2012 | Cross-referenced by PHPXref 0.7 |