[Esbox-commits] r1877 - branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards

raul at garage.maemo.org raul at garage.maemo.org
Fri Jul 17 02:19:01 EEST 2009


Author: raul
Date: 2009-07-17 02:19:00 +0300 (Fri, 17 Jul 2009)
New Revision: 1877

Added:
   branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/DownloadUtility.java
   branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/RandomFileOutputStream.java
Modified:
   branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/DownloadExecution.java
   branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/MaemoSDKVMInstaller.java
Log:
removing old targetpackageinstaller. In addition, refactor to use download thread implemented by guys from digia.

Modified: branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/DownloadExecution.java
===================================================================
--- branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/DownloadExecution.java	2009-07-16 12:52:02 UTC (rev 1876)
+++ branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/DownloadExecution.java	2009-07-16 23:19:00 UTC (rev 1877)
@@ -11,18 +11,12 @@
 package org.maemo.esbox.internal.vm.vmware.ui.wizards;
 
 import java.io.BufferedReader;
-import java.io.File;
 import java.io.IOException;
-import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;
-import java.io.RandomAccessFile;
-import java.math.BigDecimal;
-import java.net.CookieHandler;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
 import java.net.URL;
-import java.util.Locale;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -33,8 +27,6 @@
 import org.maemo.esbox.internal.vm.vmware.ui.wizards.FileDownload.Status;
 import org.maemo.mica.common.core.MicaException;
 import org.maemo.mica.common.core.Policy;
-import org.maemo.mica.common.ui.dialogs.DialogUtils;
-import org.maemo.mica.internal.maemosdk.flasher.httpconnection.SessionHandler;
 
 /**
  * This class wraps that download process of any Maemo SDK virtual image. If the
@@ -51,8 +43,9 @@
 	// progress monitor to download process
 	private IProgressMonitor progressMonitor;
 
-	private final int MAX_BUFFER_SIZE = 1024;
-
+	private static final int DOWNLOAD_TRIES = 3;
+	private static final int DOWNLOAD_WAIT = 3000; // 3 sec
+	
 	/**
 	 * Construtor.
 	 * 
@@ -92,211 +85,222 @@
 		downloadFile.cancel();
 	}
 
-	private URL getRemoteFileURL() {
-		// Get the download page so links can be properly obtained
-		String downloadPage = openDownloadPage();
-		URL remoteURL;
-		try {
-			remoteURL = getLinkFor(downloadPage, downloadFile.getDescription());
-		} catch (MalformedURLException e) {
-			Activator.getErrorLogger().logAndShowError("Invalid file URL", e);
-			return null;
-		}
-				
-		return remoteURL;
-	}
+//	private URL getRemoteFileURL() {
+//		// Get the download page so links can be properly obtained
+//		String downloadPage = openDownloadPage();
+//		URL remoteURL;
+//		try {
+//			remoteURL = getLinkFor(downloadPage, downloadFile.getDescription());
+//		} catch (MalformedURLException e) {
+//			Activator.getErrorLogger().logAndShowError("Invalid file URL", e);
+//			return null;
+//		}
+//				
+//		return remoteURL;
+//	}
+//	
+
+//	
+//	private int updateDownloadProgress(int previousProgressValue) {
+//		int progressValue = ((int) downloadFile.getProgress());
+//		if (previousProgressValue < progressValue) {
+//			previousProgressValue = progressValue;
+//			progressMonitor.worked(1);
+//		}
+//		return progressValue;
+//	}
+//	
+//	private String getTimeToFinish(double connectionSpeed) {
+//		final int MINUTE = 60;
+//		final int HOUR = 3600;
+//		int timeToFinish = (int)((downloadFile.getSize() - downloadFile.getDownloadedSize()) / connectionSpeed);
+//		String result = "";
+//		if (timeToFinish >= HOUR ) {
+//			result = ((int)timeToFinish/HOUR) + " hours and " + (timeToFinish % HOUR) + " minutes to finish";
+//		} else if (timeToFinish >= MINUTE ) {
+//			result = ((int)timeToFinish/MINUTE) + " minutes to finish";
+//		} else {
+//			result = timeToFinish + " seconds to finish";
+//		}
+//		return result;
+//	}
 	
-	private void checkPreviousDownload(String localFileName) {
-		File previousFile = new File(localFileName);
-		if (previousFile.exists()) {
-			boolean canResumeDownload = DialogUtils.showQuestionDialog(DialogUtils.getShell(), 
-					"Previous download file founded", "The file " + localFileName + " already exists. Would you like to resume download?");
-			if (canResumeDownload) {
-				downloadFile.setDownloadedSize(previousFile.length());
-			} else {
-				previousFile.delete();
-				downloadFile.setDownloadedSize(0);
-			}			
-		}
-	}
+//	private String getDownloadStatistics(String fileName, double connectionSpeed) {
+//		final int KBYTE = 1024;
+//		return "Downloading file "
+//				+ fileName
+//				+ "\n\n"
+//				+ getTimeToFinish(connectionSpeed)
+//				+ "\t"
+//				+ String.format(Locale.US, "%.2f", ((double)downloadFile.getDownloadedSize()/KBYTE))
+//				+ " KBs of " 
+//				+ String.format(Locale.US, "%.2f", ((double)downloadFile.getSize()/KBYTE)) 
+//				+ " KBs "
+//				+ String.format(Locale.US, "%.2f", connectionSpeed) + "KBs/sec"
+//				+ "\t\t"
+//				+ String.format(Locale.US, "%.2f", downloadFile.getProgress()) + "%";
+//	}
+//	
+//	private byte[] createByteBuffer() {
+//		byte[] buffer;
+//		if (downloadFile.getSize() - downloadFile.getDownloadedSize() > MAX_BUFFER_SIZE) {
+//			buffer = new byte[MAX_BUFFER_SIZE];
+//		} else {
+//			buffer = new byte[(int) (downloadFile.getSize() - downloadFile
+//					.getDownloadedSize())];
+//		}
+//		return buffer;
+//	}
+//	
+//	private double getConnectionSpeed(long time, int bytesRead) {
+//		double bytesPerMiliSeconds = (double)(bytesRead/time);
+//		return bytesPerMiliSeconds * 1000.0f;
+//	}
 	
-	private int updateDownloadProgress(int previousProgressValue) {
-		int progressValue = ((int) downloadFile.getProgress());
-		if (previousProgressValue < progressValue) {
-			previousProgressValue = progressValue;
-			progressMonitor.worked(1);
-		}
-		return progressValue;
-	}
-	
-	private String getTimeToFinish(double connectionSpeed) {
-		final int MINUTE = 60;
-		final int HOUR = 3600;
-		int timeToFinish = (int)((downloadFile.getSize() - downloadFile.getDownloadedSize()) / connectionSpeed);
-		String result = "";
-		if (timeToFinish >= HOUR ) {
-			result = ((int)timeToFinish/HOUR) + " hours and " + (timeToFinish % HOUR) + " minutes to finish";
-		} else if (timeToFinish >= MINUTE ) {
-			result = ((int)timeToFinish/MINUTE) + " minutes to finish";
-		} else {
-			result = timeToFinish + " seconds to finish";
-		}
-		return result;
-	}
-	
-	private String getDownloadStatistics(String fileName, double connectionSpeed) {
-		final int KBYTE = 1024;
-		return "Downloading file "
-				+ fileName
-				+ "\n\n"
-				+ getTimeToFinish(connectionSpeed)
-				+ "\t"
-				+ String.format(Locale.US, "%.2f", ((double)downloadFile.getDownloadedSize()/KBYTE))
-				+ " KBs of " 
-				+ String.format(Locale.US, "%.2f", ((double)downloadFile.getSize()/KBYTE)) 
-				+ " KBs "
-				+ String.format(Locale.US, "%.2f", connectionSpeed) + "KBs/sec"
-				+ "\t\t"
-				+ String.format(Locale.US, "%.2f", downloadFile.getProgress()) + "%";
-	}
-	
-	private byte[] createByteBuffer() {
-		byte[] buffer;
-		if (downloadFile.getSize() - downloadFile.getDownloadedSize() > MAX_BUFFER_SIZE) {
-			buffer = new byte[MAX_BUFFER_SIZE];
-		} else {
-			buffer = new byte[(int) (downloadFile.getSize() - downloadFile
-					.getDownloadedSize())];
-		}
-		return buffer;
-	}
-	
-	private double getConnectionSpeed(long time, int bytesRead) {
-		double bytesPerMiliSeconds = (double)(bytesRead/time);
-		return bytesPerMiliSeconds * 1000.0f;
-	}
-	
 	/**
 	 * Download the file. The process to download the file is implemented by
 	 * this method. Basically, it gets the links from download webpage. Once the
 	 * links are properly saved, the download process started. If the download
 	 * has begun, it continous from the previous state.
+	 * @throws MicaException 
 	 */
-	public void downloadFile() {
-		RandomAccessFile file = null;
-		InputStream stream = null;
-		HttpURLConnection connection = null;
+	public void downloadFile() throws MicaException {
+		
+		MicaException error = null;
+		for (int i = 1; i <= DOWNLOAD_TRIES; i++) {
+			try {
+				Thread.sleep(i * DOWNLOAD_WAIT);
+			} catch (InterruptedException e) {
 
-		try {
-			// Start cookie section from here
-			CookieHandler.setDefault(new SessionHandler());
-			
-			URL connectionURL = new URL(FileDownload.DOWNLOAD_PAGE);
-			progressMonitor.subTask("Retrieving  information from " + connectionURL.getHost());
-
-			// Get link of remote file
-			URL remoteFileURL = getRemoteFileURL();
-
-			// Check if file was downloaded before
-			progressMonitor.subTask("Checking information about file to be downloaded ...");
-			String fileName = getFileName(remoteFileURL, downloadFile.getLocalURL());
-			checkPreviousDownload(fileName);			
-			
-			// Open connection to URL.
-			progressMonitor.subTask("Establishing connection with " + remoteFileURL.getHost());
-			connection = (HttpURLConnection) remoteFileURL.openConnection();
-
-			// Specify what portion of file to download
-			connection.setRequestProperty("Range", "bytes=" + downloadFile.getDownloadedSize() + "-");
-
-			// Connect to server
-			connection.connect();
-			progressMonitor.subTask("Connected with " + remoteFileURL.getHost());
-
-			// Make sure response code is in the 200 range
-			if (connection.getResponseCode() / 100 != 2) {
-				downloadFile.error();
-				progressMonitor.setCanceled(true);
-				progressMonitor.done();
 			}
-
-			// Check for valid content length
-			int contentLength = connection.getContentLength();
-			if (contentLength < 1) {
-				downloadFile.error();
-				progressMonitor.setCanceled(true);
-				progressMonitor.done();
+			try {
+				DownloadUtility.downloadMaemoSDKImageTool(downloadFile, progressMonitor);
+			} catch (MicaException e) {
+				error = e;
 			}
-
-			progressMonitor.beginTask("File to download: "
-					+ remoteFileURL.getFile(), 100);
-
-			// Set the size for this download if it hasn't been already set.
-			if (downloadFile.getSize() == -1) {
-				downloadFile.setSize(contentLength);
-			}
-
-			// Create the local file
-			file = new RandomAccessFile(fileName, "rw");
-			file.seek(downloadFile.getDownloadedSize());
-
-			stream = connection.getInputStream();
-
-			int progressValue = 0;
-			double connectionSpeed = 0;
-			while (downloadFile.getStatus() == Status.DOWNLOADING) {
-				// Size buffer according to how much of the file is left to download
-				byte buffer[] = createByteBuffer();
-
-				long initialTime = System.currentTimeMillis();
-				int read = stream.read(buffer);
-				long finalTime = System.currentTimeMillis();
-				connectionSpeed = getConnectionSpeed(finalTime - initialTime, read);
-				if (read == -1)
-					break;
-				
-				// Write buffer to file
-				file.write(buffer, 0, read);
-				downloadFile.setDownloadedSize(downloadFile.getDownloadedSize() + read);
-				
-				// Update statistics
-				progressValue = updateDownloadProgress(progressValue);				
-				progressMonitor.subTask(getDownloadStatistics(remoteFileURL.getFile(), connectionSpeed));
-			}
-
-			// Change status to complete if this point was reached because
-			// downloading has finished.
-			if (downloadFile.getStatus() == Status.DOWNLOADING) {
-				downloadFile.complete();
-				progressMonitor.done();
-			}
-		} catch (Exception e) {
-			downloadFile.error();
-			progressMonitor.setCanceled(true);
-			progressMonitor.done();
-		} finally {
-			// Close file.
-			if (file != null) {
-				try {
-					file.close();
-				} catch (Exception e) {
-				}
-			}
-
-			// Close connection to server.
-			if (stream != null) {
-				try {
-					stream.close();
-				} catch (Exception e) {
-				}
-			}
-
-			// Close cookied section
-			CookieHandler.setDefault(null);
-
-			if (connection != null)
-				connection.disconnect();
 		}
+		if (error != null) {
+			throw error;
+		} else {
+			// Should not come here.
+			throw new MicaException("Cannot download Maemo SDK virtual image."); //$NON-NLS-1$
+		}
+		
+		
+//		RandomAccessFile file = null;
+//		InputStream stream = null;
+//		HttpURLConnection connection = null;
+//
+//		try {
+//			// Start cookie section from here
+//			CookieHandler.setDefault(new SessionHandler());
+//			
+//			URL connectionURL = new URL(FileDownload.DOWNLOAD_PAGE);
+//			progressMonitor.subTask("Retrieving  information from " + connectionURL.getHost());
+//
+//			// Get link of remote file
+//			URL remoteFileURL = getRemoteFileURL();
+//
+//			// Check if file was downloaded before
+//			progressMonitor.subTask("Checking information about file to be downloaded ...");
+//			String fileName = getFileName(remoteFileURL, downloadFile.getLocalURL());
+//			checkPreviousDownload(fileName);			
+//			
+//			// Open connection to URL.
+//			progressMonitor.subTask("Establishing connection with " + remoteFileURL.getHost());
+//			connection = (HttpURLConnection) remoteFileURL.openConnection();
+//
+//			// Specify what portion of file to download
+//			connection.setRequestProperty("Range", "bytes=" + downloadFile.getDownloadedSize() + "-");
+//
+//			// Connect to server
+//			connection.connect();
+//			progressMonitor.subTask("Connected with " + remoteFileURL.getHost());
+//
+//			// Make sure response code is in the 200 range
+//			if (connection.getResponseCode() / 100 != 2) {
+//				downloadFile.error();
+//				progressMonitor.setCanceled(true);
+//				progressMonitor.done();
+//			}
+//
+//			// Check for valid content length
+//			int contentLength = connection.getContentLength();
+//			if (contentLength < 1) {
+//				downloadFile.error();
+//				progressMonitor.setCanceled(true);
+//				progressMonitor.done();
+//			}
+//
+//			progressMonitor.beginTask("File to download: "
+//					+ remoteFileURL.getFile(), 100);
+//
+//			// Set the size for this download if it hasn't been already set.
+//			if (downloadFile.getSize() == -1) {
+//				downloadFile.setSize(contentLength);
+//			}
+//
+//			// Create the local file
+//			file = new RandomAccessFile(fileName, "rw");
+//			file.seek(downloadFile.getDownloadedSize());
+//
+//			stream = connection.getInputStream();
+//
+//			int progressValue = 0;
+//			double connectionSpeed = 0;
+//			while (downloadFile.getStatus() == Status.DOWNLOADING) {
+//				// Size buffer according to how much of the file is left to download
+//				byte buffer[] = createByteBuffer();
+//
+//				long initialTime = System.currentTimeMillis();
+//				int read = stream.read(buffer);
+//				long finalTime = System.currentTimeMillis();
+//				connectionSpeed = getConnectionSpeed(finalTime - initialTime, read);
+//				if (read == -1)
+//					break;
+//				
+//				// Write buffer to file
+//				file.write(buffer, 0, read);
+//				downloadFile.setDownloadedSize(downloadFile.getDownloadedSize() + read);
+//				
+//				// Update statistics
+//				progressValue = updateDownloadProgress(progressValue);				
+//				progressMonitor.subTask(getDownloadStatistics(remoteFileURL.getFile(), connectionSpeed));
+//			}
+//
+//			// Change status to complete if this point was reached because
+//			// downloading has finished.
+//			if (downloadFile.getStatus() == Status.DOWNLOADING) {
+//				downloadFile.complete();
+//				progressMonitor.done();
+//			}
+//		} catch (Exception e) {
+//			downloadFile.error();
+//			progressMonitor.setCanceled(true);
+//			progressMonitor.done();
+//		} finally {
+//			// Close file.
+//			if (file != null) {
+//				try {
+//					file.close();
+//				} catch (Exception e) {
+//				}
+//			}
+//
+//			// Close connection to server.
+//			if (stream != null) {
+//				try {
+//					stream.close();
+//				} catch (Exception e) {
+//				}
+//			}
+//
+//			// Close cookied section
+//			CookieHandler.setDefault(null);
+//
+//			if (connection != null)
+//				connection.disconnect();
+//		}
 	}
 
 	/**
@@ -308,7 +312,11 @@
 		while (downloadFile.getStatus() != Status.CANCELLED
 				&& downloadFile.getStatus() != Status.ERROR
 				&& downloadFile.getStatus() != Status.COMPLETE) {
-			downloadFile();
+			try {
+				downloadFile();
+			} catch (MicaException exception) {
+				Activator.getErrorLogger().logAndShowError("Cannot download Maemo SDK virtual image", exception);
+			}
 			if (downloadFile.getStatus() == Status.PAUSED) {
 				synchronized (this) {
 					try {
@@ -324,49 +332,38 @@
 		monitor.done();
 	}
 
-	/**
-	 * Get file name of download file to be saved locally
-	 * 
-	 * @param remoteURL
-	 * @param localPath
-	 * @return the name of file to be saved locally
-	 */
-	private String getFileName(URL remoteURL, URL localPath) {
-		String fileName = (new Path(remoteURL.getFile())).lastSegment();
-		fileName = fileName.substring(fileName.lastIndexOf("=") + 1);
-		return (new Path(localPath.getFile())).append(fileName).toOSString();
-	}
 
-	/**
-	 * Return the download page.
-	 * 
-	 * @return the download page.
-	 */
-	private String openDownloadPage() {
-		String responsePage = null;
-		HttpURLConnection connection = null;
-		
-		
-		try {
-			connection = connectWithPostMethod(new URL(
-					FileDownload.DOWNLOAD_PAGE));
-			responsePage = getResponse(connection);
-			if (responsePage == null) {
-				throw new MicaException("Response page is empty"); //$NON-NLS-1$
-			}
-		} catch (Exception e) {
-			Activator.getErrorLogger().logAndShowError(
-					"Cannot connect with " + FileDownload.DOWNLOAD_PAGE, e);
-			return null;
-		} finally {
+//
+//	/**
+//	 * Return the download page.
+//	 * 
+//	 * @return the download page.
+//	 */
+//	private String openDownloadPage() {
+//		String responsePage = null;
+//		HttpURLConnection connection = null;
+//		
+//		
+//		try {
+//			connection = connectWithPostMethod(new URL(
+//					FileDownload.DOWNLOAD_PAGE));
+//			responsePage = getResponse(connection);
+//			if (responsePage == null) {
+//				throw new MicaException("Response page is empty"); //$NON-NLS-1$
+//			}
+//		} catch (Exception e) {
+//			Activator.getErrorLogger().logAndShowError(
+//					"Cannot connect with " + FileDownload.DOWNLOAD_PAGE, e);
+//			return null;
+//		} finally {
+//
+//			if (connection != null)
+//				connection.disconnect();
+//
+//		}
+//		return responsePage;
+//	}
 
-			if (connection != null)
-				connection.disconnect();
-
-		}
-		return responsePage;
-	}
-
 	/**
 	 * Connect with post method on download page.
 	 * 
@@ -398,40 +395,40 @@
 			Policy.close(out);
 		}
 	}
-
-	private static String getResponse(HttpURLConnection conn)
-	throws MicaException {
-		// TODO refactor flasher on Mica so methods can be reused here.
-		if (conn == null) {
-			throw new MicaException(new IllegalArgumentException(
-			"Connection cannot be null"));
-		}
-		BufferedReader bufReader = null;
-		try {
-			bufReader = new BufferedReader(new InputStreamReader(conn
-					.getInputStream()));
-		} catch (Exception e) {
-			throw new MicaException("Cannot get input from server", e);
-		}
-		StringBuffer buffer = new StringBuffer();
-		if (bufReader != null) {
-			String inputLine;
-			try {
-				while ((inputLine = bufReader.readLine()) != null) {
-					buffer.append(inputLine);
-					buffer.append("\n"); //$NON-NLS-1$
-				}
-			} catch (IOException e) {
-				throw new MicaException("Cannot read data from server", e);
-			}
-		}
-		if (buffer.length() > 0) {
-			return buffer.toString();
-		} else {
-			return null;
-		}
-	}
-
+//
+//	private static String getResponse(HttpURLConnection conn)
+//	throws MicaException {
+//		// TODO refactor flasher on Mica so methods can be reused here.
+//		if (conn == null) {
+//			throw new MicaException(new IllegalArgumentException(
+//			"Connection cannot be null"));
+//		}
+//		BufferedReader bufReader = null;
+//		try {
+//			bufReader = new BufferedReader(new InputStreamReader(conn
+//					.getInputStream()));
+//		} catch (Exception e) {
+//			throw new MicaException("Cannot get input from server", e);
+//		}
+//		StringBuffer buffer = new StringBuffer();
+//		if (bufReader != null) {
+//			String inputLine;
+//			try {
+//				while ((inputLine = bufReader.readLine()) != null) {
+//					buffer.append(inputLine);
+//					buffer.append("\n"); //$NON-NLS-1$
+//				}
+//			} catch (IOException e) {
+//				throw new MicaException("Cannot read data from server", e);
+//			}
+//		}
+//		if (buffer.length() > 0) {
+//			return buffer.toString();
+//		} else {
+//			return null;
+//		}
+//	}
+//
 	/**
 	 * Get the links for a certain download file. It the file consists of more
 	 * than 1 file, its parts will be properly obtained.

Added: branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/DownloadUtility.java
===================================================================
--- branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/DownloadUtility.java	                        (rev 0)
+++ branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/DownloadUtility.java	2009-07-16 23:19:00 UTC (rev 1877)
@@ -0,0 +1,309 @@
+/*******************************************************************************
+ * Copyright (c) 2009 INdT, (c) 2009 Nokia Corporation
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ *    Raul Herbster (INdT) - initial API and implementation
+ *******************************************************************************/
+package org.maemo.esbox.internal.vm.vmware.ui.wizards;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.net.CookieHandler;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.Path;
+import org.maemo.esbox.internal.vm.vmware.Activator;
+import org.maemo.mica.common.core.MicaException;
+import org.maemo.mica.common.core.Policy;
+import org.maemo.mica.common.ui.dialogs.DialogUtils;
+import org.maemo.mica.internal.maemosdk.flasher.httpconnection.CopyProgressMonitor;
+import org.maemo.mica.internal.maemosdk.flasher.httpconnection.DownloadingThread;
+import org.maemo.mica.internal.maemosdk.flasher.httpconnection.SessionHandler;
+
+/**
+ * @author raulherbster
+ *
+ */
+public class DownloadUtility {
+
+	private static URL getRemoteFileURL(FileDownload downloadFile, IProgressMonitor progressMonitor) throws MicaException {
+		URL connectionURL = null;
+		try {
+			connectionURL = new URL(FileDownload.DOWNLOAD_PAGE);
+		} catch (MalformedURLException e1) {
+			throw new MicaException("Cannot define URL for Maemo SDK virtual image");
+		}
+		
+		progressMonitor.subTask("Retrieving  information from " + connectionURL.getHost());
+		
+		// Get the download page so links can be properly obtained
+		String downloadPage = openDownloadPage();
+		URL remoteURL;
+		try {
+			remoteURL = getLinkFor(downloadPage, downloadFile.getDescription());
+		} catch (MalformedURLException e) {
+			Activator.getErrorLogger().logAndShowError("Invalid file URL", e);
+			return null;
+		}
+				
+		return remoteURL;
+	}
+	
+	/**
+	 * Return the download page.
+	 * 
+	 * @return the download page.
+	 */
+	private static String openDownloadPage() {
+		String responsePage = null;
+		HttpURLConnection connection = null;
+				
+		try {
+			connection = connectWithPostMethod(new URL(
+					FileDownload.DOWNLOAD_PAGE));
+			responsePage = getResponse(connection);
+			if (responsePage == null) {
+				throw new MicaException("Response page is empty"); //$NON-NLS-1$
+			}
+		} catch (Exception e) {
+			Activator.getErrorLogger().logAndShowError(
+					"Cannot connect with " + FileDownload.DOWNLOAD_PAGE, e);
+			return null;
+		} finally {
+
+			if (connection != null)
+				connection.disconnect();
+
+		}
+		return responsePage;
+	}
+	
+	/**
+	 * Connect with post method on download page.
+	 * 
+	 * @param connectionUrl
+	 * @return
+	 * @throws MicaException
+	 */
+	private static HttpURLConnection connectWithPostMethod(URL connectionUrl) throws MicaException {
+		// TODO refactor flasher on Mica so methods can be reused here.
+		OutputStreamWriter out = null;
+		HttpURLConnection conn = null;
+		try {
+			conn = (HttpURLConnection) connectionUrl.openConnection();
+			conn.setRequestMethod("POST"); //$NON-NLS-1$
+			conn.setDoOutput(true);
+			conn.setDoInput(true);
+			conn.setRequestProperty("Content-Type",
+			"application/x-www-form-urlencoded");
+			out = new OutputStreamWriter(conn.getOutputStream());
+			out.write("agree=I accept");
+			out.flush();
+			return conn;
+		} catch (MalformedURLException e) {
+			throw new MicaException("Malformed URL", e); //$NON-NLS-1$
+		} catch (IOException e) {
+			throw new MicaException("Cannot connect to " + connectionUrl, e);
+		} finally {
+			Policy.close(out);
+		}
+	}
+	
+	private static String getResponse(HttpURLConnection conn) throws MicaException {
+		// TODO refactor flasher on Mica so methods can be reused here.
+		if (conn == null) {
+			throw new MicaException(new IllegalArgumentException(
+			"Connection cannot be null"));
+		}
+		BufferedReader bufReader = null;
+		try {
+			bufReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
+		} catch (Exception e) {
+			throw new MicaException("Cannot get input from server", e);
+		}
+		StringBuffer buffer = new StringBuffer();
+		if (bufReader != null) {
+			String inputLine;
+			try {
+				while ((inputLine = bufReader.readLine()) != null) {
+					buffer.append(inputLine);
+					buffer.append("\n"); //$NON-NLS-1$
+				}
+			} catch (IOException e) {
+				throw new MicaException("Cannot read data from server", e);
+			}
+		}
+		if (buffer.length() > 0) {
+			return buffer.toString();
+		} else {
+			return null;
+		}
+	}
+
+	
+	
+	/**
+	 * Get the links for a certain download file. It the file consists of more
+	 * than 1 file, its parts will be properly obtained.
+	 * 
+	 * @param htmlPage
+	 * @param downloadFileDescription
+	 * @return
+	 * @throws MalformedURLException
+	 */
+	private static URL getLinkFor(String htmlPage, String downloadFileDescription) throws MalformedURLException {
+		final String DOWNLOAD_FILE_PATTERN = "<tr>\\s*<td class=\"filename\">(.*?)</td>\\s*</tr>";
+		final String LINK_PATTERN = "<a href=\"(.*?)\">";
+		Pattern fileEntryPattern = Pattern.compile(DOWNLOAD_FILE_PATTERN,
+				Pattern.DOTALL | Pattern.UNIX_LINES);
+		Matcher matcher = fileEntryPattern.matcher(htmlPage);
+		while (matcher.find()) {
+			String fileInfo = matcher.group(0);
+			if (fileInfo.contains(downloadFileDescription)) {
+				Pattern hrefPattern = Pattern.compile(LINK_PATTERN,
+						Pattern.DOTALL | Pattern.UNIX_LINES);
+				Matcher matcherLink = hrefPattern.matcher(fileInfo);
+				if (matcherLink.find()) {
+					String link = matcherLink.group(1);
+					return (new URL(FileDownload.DOWNLOAD_PAGE
+							+ link.substring(link.indexOf("?"))));
+				}
+			}
+
+		}
+		return null;
+	}
+	
+	/**
+	 * Get file name of download file to be saved locally
+	 * 
+	 * @param remoteURL
+	 * @param localPath
+	 * @return the name of file to be saved locally
+	 */
+	private static String getFileName(URL remoteURL, URL localPath) {
+		String fileName = (new Path(remoteURL.getFile())).lastSegment();
+		fileName = fileName.substring(fileName.lastIndexOf("=") + 1);
+		return (new Path(localPath.getFile())).append(fileName).toOSString();
+	}
+	
+	private static long getPreviousDownload(String localFileName) {
+		File previousFile = new File(localFileName);
+		if (previousFile.exists()) {
+			boolean canResumeDownload = DialogUtils.showQuestionDialog(DialogUtils.getShell(), 
+					"Previous download file founded", "The file " + localFileName + " already exists. Would you like to resume download?");
+			if (canResumeDownload) {
+				return previousFile.length();
+			} else {
+				previousFile.delete();
+				return 0L;
+			}			
+		}
+		return 0L;
+	}
+	
+	private static void fileDownloader(FileDownload downloadFile, URL remoteURL, IProgressMonitor monitor) throws IOException, MicaException {
+		// Check if file was downloaded before
+		monitor.subTask("Checking information about file to be downloaded ...");
+		String fileName = getFileName(remoteURL, downloadFile.getLocalURL());
+		
+		downloadFile.setDownloadedSize(getPreviousDownload(fileName));			
+		
+		// Open connection to URL.
+		monitor.subTask("Establishing connection with " + remoteURL.getHost());
+		HttpURLConnection connection = (HttpURLConnection) remoteURL.openConnection();
+
+		// Specify what portion of file to download
+		connection.setRequestProperty("Range", "bytes=" + downloadFile.getDownloadedSize() + "-");
+
+		// Connect to server
+		connection.connect();
+		monitor.subTask("Connected with " + remoteURL.getHost());
+
+		// Make sure response code is in the 200 range
+		if (connection.getResponseCode() / 100 != 2) {
+			downloadFile.error();
+			monitor.setCanceled(true);
+			monitor.done();
+		}
+
+		// Check for valid content length
+		int contentLength = connection.getContentLength();
+		if (contentLength < 1) {
+			downloadFile.error();
+			monitor.setCanceled(true);
+			monitor.done();
+		}
+
+		monitor.beginTask("File to download: " + remoteURL.getFile(), 100);
+
+		// Set the size for this download if it hasn't been already set.
+		if (downloadFile.getSize() == -1) {
+			downloadFile.setSize(contentLength);
+		}
+		
+		CopyProgressMonitor progressMonitor = new CopyProgressMonitor("Downloading Maemo SDK virtual image",contentLength, monitor);
+		progressMonitor.start();
+
+		RandomFileOutputStream bos = new RandomFileOutputStream(fileName,true);
+		bos.setFilePointer(downloadFile.getDownloadedSize());
+
+		InputStream in = connection.getInputStream();
+		
+		// create and start to download
+		DownloadingThread thread = new DownloadingThread(in, bos, progressMonitor, monitor);
+		thread.start();
+
+		while (!thread.isInterrupted()) {
+			try {
+				Thread.sleep(1000);
+			} catch (InterruptedException e) {
+				continue;
+			}
+			if (monitor.isCanceled()) {
+				thread.stopDownloading();
+				throw new MicaException("Cannot continue"); //$NON-NLS-1$
+			}
+			if (!thread.isAlive()) {
+				// Downloading is done
+				break;
+			}
+		}
+		if (thread.getErrorMessage() != null) {
+			throw new IOException(thread.getErrorMessage());
+		}
+	}
+	
+	public static void downloadMaemoSDKImageTool(FileDownload downloadFile, IProgressMonitor progressMonitor) throws MicaException {
+		try {
+			CookieHandler.setDefault(new SessionHandler());
+			
+			// Get link of remote file
+			URL remoteFileURL = getRemoteFileURL(downloadFile, progressMonitor);
+
+			try {
+				fileDownloader(downloadFile,remoteFileURL,progressMonitor);
+			} catch (IOException e) {
+				throw new MicaException("Cannot dowload Maemo SDK virtual image", e);
+			}
+			
+	    } finally {
+			CookieHandler.setDefault(null);
+		}
+		
+	}
+
+}

Modified: branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/MaemoSDKVMInstaller.java
===================================================================
--- branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/MaemoSDKVMInstaller.java	2009-07-16 12:52:02 UTC (rev 1876)
+++ branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/MaemoSDKVMInstaller.java	2009-07-16 23:19:00 UTC (rev 1877)
@@ -45,7 +45,6 @@
 import org.maemo.mica.common.core.sdk.ISDKTarget;
 import org.maemo.mica.common.core.sdk.SDKManager;
 import org.maemo.mica.common.core.ui.IProgressReporter;
-import org.maemo.mica.internal.api.linux.packages.ui.aptinstall.TargetPackageInstaller;
 
 import com.nokia.cpp.internal.api.utils.ui.WorkbenchUtils;
 
@@ -403,17 +402,17 @@
 			if (targets.length != 0) {				
 				monitor.subTask("Gathering package managers...");				
 				
-				TargetPackageInstaller packageInstaller = new TargetPackageInstaller(
-						packagesToInstall,
-						new String[] {"deb http://repository.maemo.org/extras-devel/ fremantle free non-free"},
-						getBuildMachine(),
-						getBuildMachineTargets(),
-						true,
-						true,
-						true,
-						timeout,
-						reporter);
-				status = packageInstaller.ensureInstalledPackages(shell,monitor);
+//				TargetPackageInstaller packageInstaller = new TargetPackageInstaller(
+//						packagesToInstall,
+//						new String[] {"deb http://repository.maemo.org/extras-devel/ fremantle free non-free"},
+//						getBuildMachine(),
+//						getBuildMachineTargets(),
+//						true,
+//						true,
+//						true,
+//						timeout,
+//						reporter);
+//				status = packageInstaller.ensureInstalledPackages(shell,monitor);
 				
 				if (status.matches(IStatus.CANCEL)) {
 					status = Activator.createErrorStatus("The package installation was canceled.", null);

Added: branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/RandomFileOutputStream.java
===================================================================
--- branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/RandomFileOutputStream.java	                        (rev 0)
+++ branches/work_Raul/org.maemo.esbox.vm.vmware/src/org/maemo/esbox/internal/vm/vmware/ui/wizards/RandomFileOutputStream.java	2009-07-16 23:19:00 UTC (rev 1877)
@@ -0,0 +1,102 @@
+/*******************************************************************************
+ * Copyright (c) 2009 INdT, (c) 2009 Nokia Corporation
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ *    Raul Herbster (INdT) - initial API and implementation
+ *******************************************************************************/
+package org.maemo.esbox.internal.vm.vmware.ui.wizards;
+
+/**
+ * @author raulherbster
+ *
+ */
+import java.io.*;
+
+public class RandomFileOutputStream extends OutputStream {
+
+	protected RandomAccessFile randomFile; 
+	protected boolean sync;
+
+	public RandomFileOutputStream(String fnm) throws IOException {
+		this(fnm, false);
+	}
+
+	public RandomFileOutputStream(String fnm, boolean syn) throws IOException {
+		this(new File(fnm), syn);
+	}
+
+	public RandomFileOutputStream(File fil) throws IOException {
+		this(fil, false);
+	}
+
+	public RandomFileOutputStream(File fil, boolean syn) throws IOException {
+		super();
+
+		fil = fil.getAbsoluteFile();
+		
+		File par; // parent file
+		
+		if ((par = fil.getParentFile()) != null) {
+			par.mkdir();
+		}
+		
+		randomFile = new RandomAccessFile(fil, "rw");
+		sync = syn;
+	}
+
+	public void write(int val) throws IOException {
+		randomFile.write(val);
+		if (sync) {
+			randomFile.getFD().sync();
+		}
+	}
+
+	public void write(byte[] val) throws IOException {
+		randomFile.write(val);
+		if (sync) {
+			randomFile.getFD().sync();
+		}
+	}
+
+	public void write(byte[] val, int off, int len) throws IOException {
+		randomFile.write(val, off, len);
+		if (sync) {
+			randomFile.getFD().sync();
+		}
+	}
+
+	public void flush() throws IOException {
+		if (sync) {
+			randomFile.getFD().sync();
+		}
+	}
+
+	public void close() throws IOException {
+		randomFile.close();
+	}
+
+	public long getFilePointer() throws IOException {
+		return randomFile.getFilePointer();
+	}
+
+	public void setFilePointer(long pos) throws IOException {
+		randomFile.seek(pos);
+	}
+
+	public long getFileSize() throws IOException {
+		return randomFile.length();
+	}
+
+	public void setFileSize(long len) throws IOException {
+		randomFile.setLength(len);
+	}
+
+	public FileDescriptor getFD() throws IOException {
+		return randomFile.getFD();
+	}
+
+} // END PUBLIC CLASS
\ No newline at end of file



More information about the Esbox-commits mailing list