diff options
Diffstat (limited to 'dozentenmodul')
15 files changed, 608 insertions, 966 deletions
diff --git a/dozentenmodul/pom.xml b/dozentenmodul/pom.xml index 6dbdbb1d..b87d729d 100644 --- a/dozentenmodul/pom.xml +++ b/dozentenmodul/pom.xml @@ -201,12 +201,6 @@ <scope>compile</scope> </dependency> <dependency> - <groupId>commons-net</groupId> - <artifactId>commons-net</artifactId> - <version>3.3</version> - <scope>compile</scope> - </dependency> - <dependency> <groupId>com.toedter</groupId> <artifactId>jcalendar</artifactId> <version>1.4</version> @@ -244,7 +238,7 @@ <dependency> <groupId>org.openslx.bwlp</groupId> <artifactId>master-sync-shared</artifactId> - <version>1.0-SNAPSHOT</version> + <version>1.1-SNAPSHOT</version> <scope>compile</scope> </dependency> <dependency> diff --git a/dozentenmodul/src/main/java/ftp/DownloadTask.java b/dozentenmodul/src/main/java/ftp/DownloadTask.java index ef95b8da..95e74169 100644 --- a/dozentenmodul/src/main/java/ftp/DownloadTask.java +++ b/dozentenmodul/src/main/java/ftp/DownloadTask.java @@ -4,10 +4,9 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; import java.io.InputStreamReader; +import java.io.RandomAccessFile; import java.nio.charset.StandardCharsets; import java.util.Map; @@ -20,6 +19,10 @@ import models.SessionData; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.apache.thrift.TException; +import org.openslx.filetransfer.DataReceivedCallback; +import org.openslx.filetransfer.Downloader; +import org.openslx.filetransfer.FileRange; +import org.openslx.filetransfer.WantRangeCallback; import org.openslx.thrifthelper.ThriftManager; import util.ResourceLoader; @@ -37,27 +40,78 @@ public class DownloadTask extends SwingWorker<Void, Void> { */ private final static Logger LOGGER = Logger.getLogger(DownloadTask.class); - private static final int BUFFER_SIZE = 8 * 1024 * 1024; private static final double UPDATE_INTERVAL_SECONDS = 0.6; private static final double UPDATE_INTERVAL_MS = UPDATE_INTERVAL_SECONDS * 1000; private static final double BYTES_PER_MIB = 1024 * 1024; + private static final long CHUNK_SIZE = 16 * 1024 * 1024; - private String host; - private int port; - private String username; - private String password; - private String downloadPath; - private String saveDir; - private int percentCompleted; + private final String host; + private final int port; + private final String downloadToken; + private final String saveDir; + private final long fileSize; + private boolean success = false; - public DownloadTask(String host, int port, String username, String password, - String downloadPath, String saveDir) { + public DownloadTask(String host, int port, String downloadToken, String saveDir, long fileSize) { this.host = host; this.port = port; - this.username = username; - this.password = password; - this.downloadPath = downloadPath; + this.downloadToken = downloadToken; this.saveDir = saveDir; + this.fileSize = fileSize; + } + + class Callbacks implements WantRangeCallback, DataReceivedCallback { + // initialize the counters needed for speed calculations + private long currentRequestedOffset = -1; + private long totalBytesRead = 0; + private long lastUpdate = 0; + private long lastBytes = 0; + private long currentBytes = 0; + private final RandomAccessFile file; + + public Callbacks(RandomAccessFile file) { + this.file = file; + } + + @Override + public FileRange get() { + if (currentRequestedOffset == -1) + currentRequestedOffset = 0; + else + currentRequestedOffset += CHUNK_SIZE; + if (currentRequestedOffset >= fileSize) + return null; + long end = currentRequestedOffset + CHUNK_SIZE; + if (end > fileSize) + end = fileSize; + return new FileRange(currentRequestedOffset, end); + } + + @Override + public boolean dataReceived(final long fileOffset, final int dataLength, final byte[] data) { + try { + file.seek(fileOffset); + file.write(data, 0, dataLength); + } catch (Exception e) { + LOGGER.error("Could not write to file at offset " + fileOffset, e); + return false; + } + currentBytes += dataLength; + totalBytesRead += dataLength; + final long now = System.currentTimeMillis(); + if (lastUpdate + UPDATE_INTERVAL_MS < now) { + final int percentCompleted = (int) ((totalBytesRead * 100) / fileSize); + setProgress(percentCompleted); + lastBytes = (lastBytes * 2 + currentBytes) / 3; + final double speed = lastBytes / UPDATE_INTERVAL_SECONDS; + firePropertyChange("speed", 0, speed / BYTES_PER_MIB); + firePropertyChange("bytesread", 0, totalBytesRead); + lastUpdate = now; + currentBytes = 0; + } + return true; + } + } /** @@ -65,61 +119,45 @@ public class DownloadTask extends SwingWorker<Void, Void> { */ @Override protected Void doInBackground() throws Exception { - FTPUtility util = new FTPUtility(host, port, username, password); - try { - util.connect(); + boolean ret = false; + // show filesize in the GUI + firePropertyChange("filesize", 0, fileSize); - // show filesize in the GUI - long fileSize = util.getFileSize(downloadPath); - firePropertyChange("filesize", 0, fileSize); - util.downloadFile(downloadPath); + Downloader download = null; + RandomAccessFile file = null; + try { + download = new Downloader(host, port, null, downloadToken); // TODO: SSL + try { + file = new RandomAccessFile(new File(saveDir), "rw"); + } catch (Exception e2) { + JOptionPane.showMessageDialog(null, "Could not open destination file:\n" + saveDir + "\n" + + e2.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + e2.printStackTrace(); + setProgress(0); + return null; + } - // prepare the input/output streams - String fileName = new File(downloadPath).getName(); - File downloadFile = new File(saveDir + File.separator + fileName); - FileOutputStream outputStream = new FileOutputStream(downloadFile); - InputStream inputStream = util.getInputStream(); + Callbacks cb = new Callbacks(file); - // initialize the counters needed for speed calculations - percentCompleted = 0; - byte[] buffer = new byte[BUFFER_SIZE]; - int bytesRead = -1; - long totalBytesRead = 0; - long lastUpdate = 0; - long lastBytes = 0; - long currentBytes = 0; - while ((bytesRead = inputStream.read(buffer)) != -1 && !isCancelled()) { - outputStream.write(buffer, 0, bytesRead); - currentBytes += bytesRead; - totalBytesRead += bytesRead; - long now = System.currentTimeMillis(); - if (lastUpdate + UPDATE_INTERVAL_MS < now) { - percentCompleted = (int) ((totalBytesRead * 100) / fileSize); - setProgress(percentCompleted); - lastBytes = (lastBytes * 2 + currentBytes) / 3; - final double speed = lastBytes / UPDATE_INTERVAL_SECONDS; - firePropertyChange("speed", 0, speed / BYTES_PER_MIB); - firePropertyChange("bytesread", 0, totalBytesRead); - lastUpdate = now; - currentBytes = 0; + ret = download.download(cb, cb); + } finally { + if (file != null) { + try { + file.close(); + } catch (Exception e) { } } - // finalize the download by updating the progress bar one last time - // (in case we didn't get to do it because of the time interval) - percentCompleted = (int) ((totalBytesRead * 100) / fileSize); - setProgress(percentCompleted); - firePropertyChange("bytesread", 0, totalBytesRead); - outputStream.close(); - util.finish(); - } catch (FTPException ex) { - JOptionPane.showMessageDialog(null, - "Error downloading file: " + ex.getMessage(), "Error", - JOptionPane.ERROR_MESSAGE); - ex.printStackTrace(); - setProgress(0); - cancel(true); - } finally { - util.disconnect(); + if (download != null) + download.close(null); + } + + // if the download succeeded, set the progress to 100% manually again here to make + // sure the GUI knows about it. + if (ret) { + setProgress(100); + firePropertyChange("bytesread", 0, fileSize); + firePropertyChange("success", false, true); + success = true; } return null; @@ -130,24 +168,26 @@ public class DownloadTask extends SwingWorker<Void, Void> { */ @Override protected void done() { - if (!isCancelled() && percentCompleted == 100) { + if (isCancelled()) + return; + if (success) { LOGGER.info("Datei erfolgreich heruntergeladen."); String vmxResult = ""; - vmxResult = generateVmx() ? "Passende VMX generiert." - : "Keine passende VMX generiert!"; - JOptionPane.showMessageDialog(null, "Datei erfolgreich heruntergeladen. " - + vmxResult, "Message", JOptionPane.INFORMATION_MESSAGE); - } else if (!isCancelled() && percentCompleted != 100) { + vmxResult = generateVmx() ? "Passende VMX generiert." : "Keine passende VMX generiert!"; + JOptionPane.showMessageDialog(null, "Datei erfolgreich heruntergeladen. " + vmxResult, "Message", + JOptionPane.INFORMATION_MESSAGE); + } else { LOGGER.error("Datei wurde unvollständig heruntergeladen."); JOptionPane.showMessageDialog(null, - "Datei wurde unvollständig heruntergeladen. Bitte wiederholen.", - "Message", JOptionPane.INFORMATION_MESSAGE); + "Datei wurde unvollständig heruntergeladen. Bitte wiederholen.", "Message", + JOptionPane.INFORMATION_MESSAGE); } } /** * Helper to generate the vmx for the downloaded image - * + * TODO: Not really related to DownloadTask... + * * @return true|false indicating the success of the file creation */ private boolean generateVmx() { @@ -159,8 +199,7 @@ public class DownloadTask extends SwingWorker<Void, Void> { LOGGER.debug("Image's ID: " + Image.ImageId); Map<String, String> imageData = null; try { - imageData = ThriftManager.getSatClient().getImageData( - Image.ImageId, Image.Version, + imageData = ThriftManager.getSatClient().getImageData(Image.ImageId, Image.Version, SessionData.authToken); } catch (TException e) { LOGGER.error("Thrift exception during transfer, see trace: ", e); @@ -177,37 +216,29 @@ public class DownloadTask extends SwingWorker<Void, Void> { int hardwareVersion = extractHardwareVersion(saveDir + File.separator + imageData.get("path").replaceFirst("^prod/", "")); if (hardwareVersion == 0) { - LOGGER - .error("'extractHardwareVersion' returned 0 indicating some problem. See logs."); + LOGGER.error("'extractHardwareVersion' returned 0 indicating some problem. See logs."); LOGGER.error("Falling back to default hardware version of '10'."); hardwareVersion = 10; } // TODO: sanity checks on the content of imageData would be good here... // use the information we received about the image - vmxTemplate = vmxTemplate.replace("%VM_DISPLAY_NAME%", - imageData.get("name")); + vmxTemplate = vmxTemplate.replace("%VM_DISPLAY_NAME%", imageData.get("name")); vmxTemplate = vmxTemplate.replace("%VM_GUEST_OS%", imageData.get("os")); vmxTemplate = vmxTemplate.replace("%VM_CPU_COUNT%", imageData.get("cpu")); vmxTemplate = vmxTemplate.replace("%VM_RAM_SIZE%", String.valueOf(Integer.valueOf(imageData.get("ram")) * 1024)); - vmxTemplate = vmxTemplate.replace("%VM_DISK_PATH%", imageData.get("path") - .replaceFirst("^prod/", "")); - vmxTemplate = vmxTemplate.replace("%VM_HW_VERSION%", - String.valueOf(hardwareVersion)); + vmxTemplate = vmxTemplate.replace("%VM_DISK_PATH%", imageData.get("path").replaceFirst("^prod/", "")); + vmxTemplate = vmxTemplate.replace("%VM_HW_VERSION%", String.valueOf(hardwareVersion)); // build filename for the vmx, basicly the same as the path of the vmdk // just without the leading "prod/" and "vmx" instead of "vmdk" at the end. - String targetFilename = saveDir - + File.separator - + imageData.get("path").replaceFirst("^prod/", "") - .replaceFirst("\\.vmdk$", "") + ".vmx"; + String targetFilename = saveDir + File.separator + + imageData.get("path").replaceFirst("^prod/", "").replaceFirst("\\.vmdk$", "") + ".vmx"; try { // try to write it to file - FileUtils.writeStringToFile(new File(targetFilename), vmxTemplate, - StandardCharsets.UTF_8); + FileUtils.writeStringToFile(new File(targetFilename), vmxTemplate, StandardCharsets.UTF_8); } catch (IOException e) { - LOGGER.error("Could not write vmx-template to '" + targetFilename - + "'. See trace: ", e); + LOGGER.error("Could not write vmx-template to '" + targetFilename + "'. See trace: ", e); return false; } return true; @@ -216,44 +247,41 @@ public class DownloadTask extends SwingWorker<Void, Void> { /** * Helper to extract the hardware version of the VMDK file by inspecting its * content. - * - * @return value of hardware version as integer. A return value of 0 indicates + * + * @return value of hardware version as integer. A return value of 0 + * indicates * an error. */ private int extractHardwareVersion(String path) { BufferedReader br = null; try { try { - br = new BufferedReader( - new InputStreamReader(new FileInputStream(path))); + br = new BufferedReader(new InputStreamReader(new FileInputStream(path))); String line; // first 4 characters of a VMDK file start with 'KDMV' // first lets check if this is the case line = br.readLine(); if (!line.subSequence(0, 4).equals("KDMV")) { - LOGGER - .error("Did not see 'KDMV' as first chars of the VMDK! Returning 0."); + LOGGER.error("Did not see 'KDMV' as first chars of the VMDK! Returning 0."); LOGGER.debug("First line was: " + line); LOGGER.debug("First 4 characters of it: " + line.subSequence(0, 4)); return 0; } - // only read a maximum of 20 lines, just in case... + // only read a maximum of 25 lines, just in case... int round = 0; - while ((line = br.readLine()) != null && round < 20) { - if (line.matches("^ddb\\.virtualHWVersion.*")) { + while ((line = br.readLine()) != null && round < 25) { + if (line.startsWith("ddb.virtualHWVersion")) { String[] tmp = line.split("="); // we should get 2 strings only after the split, lets be sure if (tmp.length != 2) { - LOGGER - .debug("Splitting returned more than 2 parts, this should not happen!"); + LOGGER.debug("Splitting returned more than 2 parts, this should not happen!"); return 0; } int candidate = Integer.parseInt(tmp[1].trim().replace("\"", "")); LOGGER.debug("Considering hardware version: " + candidate); if (candidate > 0) { - LOGGER - .debug("Valid value of the candidate. Using hardware version of: " - + candidate); + LOGGER.debug("Valid value of the candidate. Using hardware version of: " + + candidate); return candidate; } else { LOGGER.error("Candidate is not > 0! Returning 0."); @@ -262,8 +290,10 @@ public class DownloadTask extends SwingWorker<Void, Void> { } round++; } - LOGGER.error("Failed to find hardware version. Tried " + round - + " rounds."); + LOGGER.error("Failed to find hardware version. Tried " + round + " rounds."); + } catch (NumberFormatException e) { + // Not a number? + return 0; } finally { br.close(); } diff --git a/dozentenmodul/src/main/java/ftp/FTPException.java b/dozentenmodul/src/main/java/ftp/FTPException.java deleted file mode 100644 index bc3193e0..00000000 --- a/dozentenmodul/src/main/java/ftp/FTPException.java +++ /dev/null @@ -1,8 +0,0 @@ -package ftp; - -@SuppressWarnings("serial") -public class FTPException extends Exception { - public FTPException(String message) { - super(message); - } -}
\ No newline at end of file diff --git a/dozentenmodul/src/main/java/ftp/FTPUtility.java b/dozentenmodul/src/main/java/ftp/FTPUtility.java deleted file mode 100644 index a7f48e4d..00000000 --- a/dozentenmodul/src/main/java/ftp/FTPUtility.java +++ /dev/null @@ -1,197 +0,0 @@ -package ftp; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.NoSuchAlgorithmException; - -import models.Image; - -import org.apache.commons.net.ftp.FTP; -import org.apache.commons.net.ftp.FTPFile; -import org.apache.commons.net.ftp.FTPReply; -import org.apache.commons.net.ftp.FTPSClient; - -/** - * A utility class that provides functionality for downloading files from a FTP - * server. - * - * @author www.codejava.net - * - */ -public class FTPUtility { - - // FTP server information - private String host; - private int port; - private String username; - private String password; - - private FTPSClient ftpClient = new FTPSClient(); - private int replyCode; - - private InputStream inputStream; - private OutputStream outputStream; - - public FTPUtility(String host, int port, String user, String pass) { - this.host = host; - this.port = port; - this.username = user; - this.password = pass; - this.ftpClient.setBufferSize(0); - } - - /** - * Connect and login to the server. - * - * @throws FTPException - * @throws NoSuchAlgorithmException - */ - public void connect() throws FTPException, NoSuchAlgorithmException { - try { - ftpClient.connect(host, port); - replyCode = ftpClient.getReplyCode(); - if (!FTPReply.isPositiveCompletion(replyCode)) { - throw new FTPException("FTP server refused connection."); - } - - boolean logged = ftpClient.login(username, password); - if (!logged) { - // failed to login - ftpClient.execPROT("P"); - ftpClient.disconnect(); - throw new FTPException("Could not login to the server."); - } - - ftpClient.enterLocalPassiveMode(); - - } catch (IOException ex) { - throw new FTPException("I/O error: " + ex.getMessage()); - } - } - - /** - * Gets size (in bytes) of the file on the server. - * - * @param filePath - * Path of the file on server - * @return file size in bytes - * @throws FTPException - */ - public long getFileSize(String filePath) throws FTPException { - try { - FTPFile file = ftpClient.mlistFile(filePath); - if (file == null) { - throw new FTPException("The file may not exist on the server!"); - } - return file.getSize(); - } catch (IOException ex) { - throw new FTPException("Could not determine size of the file: " - + ex.getMessage()); - } - } - - /** - * Start downloading a file from the server - * - * @param downloadPath - * Full path of the file on the server - * @throws FTPException - * if client-server communication error occurred - */ - public void downloadFile(String downloadPath) throws FTPException { - try { - - boolean success = ftpClient.setFileType(FTP.BINARY_FILE_TYPE); - if (!success) { - throw new FTPException("Could not set binary file type."); - } - - inputStream = ftpClient.retrieveFileStream(downloadPath); - - if (inputStream == null) { - throw new FTPException( - "Could not open input stream. The file may not exist on the server."); - } - } catch (IOException ex) { - throw new FTPException("Error downloading file: " + ex.getMessage()); - } - } - - /** - * Start uploading a file to the server - * - * @param uploadFile - * the file to be uploaded - * @param destDir - * destination directory on the server where the file is stored - * @throws FTPException - * if client-server communication error occurred - */ - public void uploadFile(File uploadFile, String destDir) throws FTPException { - try { - boolean success = ftpClient.changeWorkingDirectory(destDir); - if (!success) { - throw new FTPException("Could not change working directory to " - + destDir + ". The directory may not exist."); - } - - success = ftpClient.setFileType(FTP.BINARY_FILE_TYPE); - if (!success) { - throw new FTPException("Could not set binary file type."); - } - - outputStream = ftpClient.storeFileStream(Image.NewName); - - // ftpClient.rename(uploadFile.getName(), ); - } catch (IOException ex) { - throw new FTPException("Error uploading file: " + ex.getMessage()); - } - } - - /** - * Write an array of bytes to the output stream. - */ - public void writeFileBytes(byte[] bytes, int offset, int length) - throws IOException { - outputStream.write(bytes, offset, length); - } - - /** - * Complete the download operation. - */ - public void finish() throws IOException { - inputStream.close(); - ftpClient.completePendingCommand(); - } - - /** - * Log out and disconnect from the server - */ - public void disconnect() throws FTPException { - if (ftpClient.isConnected()) { - try { - if (!ftpClient.logout()) { - throw new FTPException("Could not log out from the server"); - } - ftpClient.disconnect(); - } catch (IOException ex) { - throw new FTPException("Error disconnect from the server: " - + ex.getMessage()); - } - } - } - - /** - * Return InputStream of the remote file on the server. - */ - public InputStream getInputStream() { - return inputStream; - } - - public OutputStream getOutputStream() { - return outputStream; - } - -}
\ No newline at end of file diff --git a/dozentenmodul/src/main/java/ftp/UploadTask.java b/dozentenmodul/src/main/java/ftp/UploadTask.java index 61f81c3b..7069db29 100644 --- a/dozentenmodul/src/main/java/ftp/UploadTask.java +++ b/dozentenmodul/src/main/java/ftp/UploadTask.java @@ -1,15 +1,17 @@ package ftp; import java.io.File; -import java.io.FileInputStream; +import java.io.IOException; import javax.swing.JOptionPane; import javax.swing.SwingWorker; -import org.apache.log4j.Logger; - import models.Image; +import org.apache.log4j.Logger; +import org.openslx.filetransfer.UploadStatusCallback; +import org.openslx.filetransfer.Uploader; + /** * Executes the file upload in a background thread and updates progress to * listeners that implement the java.beans.PropertyChangeListener interface. @@ -24,26 +26,21 @@ public class UploadTask extends SwingWorker<Void, Void> { */ private final static Logger LOGGER = Logger.getLogger(UploadTask.class); - private static final int BUFFER_SIZE = 1024 * 1024; private static final double UPDATE_INTERVAL_SECONDS = 0.6; private static final double UPDATE_INTERVAL_MS = UPDATE_INTERVAL_SECONDS * 1000; private static final double BYTES_PER_MIB = 1024 * 1024; - private String host; - private int port; - private String username; - private String password; - private String destDir; - private File uploadFile; - private int percentCompleted; + private final String host; + private final int port; + private final String uploadToken; + private final File uploadFile; + private boolean success = false; - public UploadTask(String host, int port, String username, String password, - String destDir, File uploadFile) { + public UploadTask(String host, int port, String uploadToken, File uploadFile) { + // TODO: SSL this.host = host; this.port = port; - this.username = username; - this.password = password; - this.destDir = destDir; + this.uploadToken = uploadToken; this.uploadFile = uploadFile; } @@ -52,60 +49,63 @@ public class UploadTask extends SwingWorker<Void, Void> { * Executed in background thread */ @Override - protected Void doInBackground() throws Exception { - FTPUtility util = new FTPUtility(host, port, username, password); + protected Void doInBackground() { + Uploader upload = null; try { - util.connect(); - util.uploadFile(uploadFile, destDir); - - // show filesize in the GUI - long fileSize = uploadFile.length(); - Image.Filesize = fileSize; - firePropertyChange("filesize", 0, fileSize); - - // prepare input stream - FileInputStream inputStream = new FileInputStream(uploadFile); - - // initialize the counters needed for speed calculations - percentCompleted = 0; - byte[] buffer = new byte[BUFFER_SIZE]; - int bytesRead = -1; - long totalBytesRead = 0; - long lastUpdate = 0; - long lastBytes = 0; - long currentBytes = 0; - while ((bytesRead = inputStream.read(buffer)) != -1 && !isCancelled()) { - util.writeFileBytes(buffer, 0, bytesRead); - currentBytes += bytesRead; - totalBytesRead += bytesRead; - long now = System.currentTimeMillis(); - if (lastUpdate + UPDATE_INTERVAL_MS < now) { - percentCompleted = (int) ((totalBytesRead * 100) / fileSize); - setProgress(percentCompleted); - lastBytes = (lastBytes * 2 + currentBytes) / 3; - final double speed = lastBytes / UPDATE_INTERVAL_SECONDS; - firePropertyChange("speed", 0, speed / BYTES_PER_MIB); - firePropertyChange("bytesread", 0, totalBytesRead); - lastUpdate = now; - currentBytes = 0; + upload = new Uploader(host, port, null, uploadToken); // TODO: SSL + + final Uploader ul = upload; + final long fileSize = Image.Filesize = uploadFile.length(); + firePropertyChange("filesize", 0, fileSize); // Updates GUI + + final boolean ret = upload.upload(uploadFile.getAbsolutePath(), new UploadStatusCallback() { + // progress counter + private long totalBytesRead = 0; + // initialize the counters needed for speed calculations + private long lastUpdate = 0; + private long lastBytes = 0; + private long currentBytes = 0; + + @Override + public void uploadProgress(long bytesSent) { + totalBytesRead += bytesSent; + currentBytes += bytesSent; + final long now = System.currentTimeMillis(); + if (lastUpdate + UPDATE_INTERVAL_MS < now) { + final int percentCompleted = (int) ((totalBytesRead * 100) / fileSize); + setProgress(percentCompleted); + lastBytes = (lastBytes * 2 + currentBytes) / 3; + final double speed = lastBytes / UPDATE_INTERVAL_SECONDS; + firePropertyChange("speed", 0, speed / BYTES_PER_MIB); + firePropertyChange("bytesread", 0, totalBytesRead); + lastUpdate = now; + currentBytes = 0; + } } + + @Override + public void uploadError(String message) { + JOptionPane.showMessageDialog(null, "Error uploading file: " + message, "Error", + JOptionPane.ERROR_MESSAGE); + ul.close(null); + } + }); + + // if the upload succeeded, set the progress to 100% manually again here to make + // sure the GUI knows about it. + if (ret) { + setProgress(100); + firePropertyChange("bytesread", 0, uploadFile.length()); + firePropertyChange("success", false, true); + success = true; } - // finalize the upload by updating the progress bar one last time - // (in case we didn't get to do it because of the time interval) - percentCompleted = (int) ((totalBytesRead * 100) / fileSize); - setProgress(percentCompleted); - firePropertyChange("bytesread", 0, totalBytesRead); - inputStream.close(); - util.finish(); - } catch (FTPException ex) { - JOptionPane.showMessageDialog(null, - "Error uploading file: " + ex.getMessage(), "Error", + } catch (IOException e) { + JOptionPane.showMessageDialog(null, "Error uploading file: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); - ex.printStackTrace(); - setProgress(0); - cancel(true); + LOGGER.error("Upload of " + uploadFile.getAbsolutePath() + " failed!", e); } finally { - util.disconnect(); + if (upload != null) + upload.close(null); } return null; @@ -116,14 +116,15 @@ public class UploadTask extends SwingWorker<Void, Void> { */ @Override protected void done() { - if (!isCancelled() && percentCompleted == 100) { + if (isCancelled()) + return; + if (success) { LOGGER.info("Datei erfolgreich hochgeladen."); - JOptionPane.showMessageDialog(null, "Datei erfolgreich hochgeladen.", - "Message", JOptionPane.INFORMATION_MESSAGE); - } else if (!isCancelled() && percentCompleted != 100) { + JOptionPane.showMessageDialog(null, "Datei erfolgreich hochgeladen.", "Message", + JOptionPane.INFORMATION_MESSAGE); + } else { LOGGER.error("Datei wurde unvollständig hochgeladen."); - JOptionPane.showMessageDialog(null, - "Datei wurde unvollständig hochgeladen. Bitte wiederholen.", + JOptionPane.showMessageDialog(null, "Datei wurde unvollständig hochgeladen. Bitte wiederholen.", "Message", JOptionPane.INFORMATION_MESSAGE); } } diff --git a/dozentenmodul/src/main/java/gui/image/DeleteImage_GUI.java b/dozentenmodul/src/main/java/gui/image/DeleteImage_GUI.java index 21128e48..cf448f70 100644 --- a/dozentenmodul/src/main/java/gui/image/DeleteImage_GUI.java +++ b/dozentenmodul/src/main/java/gui/image/DeleteImage_GUI.java @@ -6,7 +6,6 @@ import gui.intro.MainMenue_GUI; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; -import java.awt.HeadlessException; import java.awt.SystemColor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -163,8 +162,7 @@ public class DeleteImage_GUI extends JInternalFrame { JTextPane txtpnBitteWhlenSie = new JTextPane(); txtpnBitteWhlenSie.setEditable(false); txtpnBitteWhlenSie.setBackground(SystemColor.menu); - txtpnBitteWhlenSie - .setText("Wählen Sie bitte aus der unten stehenden Liste das zu löschende Image aus."); + txtpnBitteWhlenSie.setText("Wählen Sie bitte aus der unten stehenden Liste das zu löschende Image aus."); txtpnBitteWhlenSie.setBounds(10, 36, 509, 32); panel.add(txtpnBitteWhlenSie); } @@ -291,97 +289,72 @@ public class DeleteImage_GUI extends JInternalFrame { String imageversion = ""; int eingabe; - if (tablemyImages.getSelectedRowCount() != 0) { - - // frage, soll das selektierte Daten geloescht werden? - eingabe = JOptionPane.showConfirmDialog(null, "Wollen Sie diese Daten löschen?", - "Löschen?", JOptionPane.YES_NO_OPTION); - - if (eingabe == JOptionPane.YES_OPTION) { - - imageid = modelMyImages.getValueAt( - tablemyImages.convertRowIndexToModel(tablemyImages.getSelectedRow()), 6) - .toString(); - - imageversion = modelMyImages.getValueAt( - tablemyImages.convertRowIndexToModel(tablemyImages.getSelectedRow()), 7) - .toString(); - - // Image darf nur geloescht werden, wenn keine - // Veranstaltung mehr auf das Image verweist. - // Unbdingt abfragen! - - try { - if (!ThriftManager.getSatClient().connectedToLecture(imageid, imageversion, - SessionData.authToken)) { - try { - - // try to delete file from file system - if (ThriftManager.getSatClient().deleteImageServer(imageid, imageversion, - SessionData.authToken) == true) { - // successful, now delete file from DB - if (ThriftManager.getSatClient().deleteImageData(imageid, - imageversion, SessionData.authToken)) { - - LOGGER.info("Image '" + imageid + "' erfolgreich gelöscht."); - - GuiManager.show(new DeleteImage_GUI()); - } else { - //could not delete file from DB - LOGGER.info("Image '" + imageid - + "' konnte nicht gelöscht werden."); - - JOptionPane.showMessageDialog(null, - "Image konnte nicht gelöscht werden.", "Fehler", - JOptionPane.INFORMATION_MESSAGE); - } - } else { - // could not delete file from file - // system - LOGGER.info("Image '" + imageid - + "' konnte nicht von Server gelöscht werden."); - - JOptionPane.showMessageDialog(null, - "Image konnte nicht vom Server gelöscht werden.", "Fehler", - JOptionPane.INFORMATION_MESSAGE); - } - - } catch (HeadlessException e) { - - e.printStackTrace(); - JOptionPane.showMessageDialog(null, - e.getCause() + "\n" + e.getStackTrace(), "Debug-Message", - JOptionPane.ERROR_MESSAGE); - } catch (TException e) { - - e.printStackTrace(); - JOptionPane.showMessageDialog(null, - e.getCause() + "\n" + e.getStackTrace(), "Debug-Message", - JOptionPane.ERROR_MESSAGE); - } - - } else { - LOGGER.info("Image '" - + imageid - + "' konnte nicht gelöscht werden, da mindestens eine Veranstaltung mit diesem Image verlinkt ist."); - - JOptionPane - .showMessageDialog( - null, - "Image kann nicht gelöscht werden, da mindestens eine Veranstaltung mit diesem Image verlinkt ist.", - "Verlinkung vorhanden", JOptionPane.INFORMATION_MESSAGE); - } - } catch (TException e) { - - e.printStackTrace(); - JOptionPane.showMessageDialog(null, e.getCause() + "\n" + e.getStackTrace(), - "Debug-Message", JOptionPane.ERROR_MESSAGE); - } + if (tablemyImages.getSelectedRowCount() != 1) { + JOptionPane.showMessageDialog(null, "Bitte wählen Sie ein Image aus", "Info", + JOptionPane.INFORMATION_MESSAGE); + return; + } + + // frage, soll das selektierte Daten geloescht werden? + eingabe = JOptionPane.showConfirmDialog(null, "Wollen Sie diese Daten löschen?", "Löschen?", + JOptionPane.YES_NO_OPTION); + + if (eingabe != JOptionPane.YES_OPTION) { + return; + } + + imageid = modelMyImages.getValueAt( + tablemyImages.convertRowIndexToModel(tablemyImages.getSelectedRow()), 6).toString(); + + imageversion = modelMyImages.getValueAt( + tablemyImages.convertRowIndexToModel(tablemyImages.getSelectedRow()), 7).toString(); + + // Image darf nur geloescht werden, wenn keine + // Veranstaltung mehr auf das Image verweist. + // Unbdingt abfragen! + // TODO: Check this server side on delete, then using exceptions... + try { + if (ThriftManager.getSatClient().connectedToLecture(imageid, imageversion, + SessionData.authToken)) { + LOGGER.info("Image '" + imageid + + "' konnte nicht gelöscht werden, da mindestens eine Veranstaltung mit" + + " diesem Image verlinkt ist."); + + JOptionPane.showMessageDialog(null, + "Image kann nicht gelöscht werden, da mindestens eine Veranstaltung mit" + + " diesem Image verlinkt ist.", "Verlinkung vorhanden", + JOptionPane.INFORMATION_MESSAGE); + return; } + } catch (Exception e) { + } + + try { + // try to delete file from file system + if (ThriftManager.getSatClient() + .deleteImage(imageid, imageversion, SessionData.authToken) == true) { + LOGGER.info("Image '" + imageid + "' erfolgreich gelöscht."); + + GuiManager.show(new DeleteImage_GUI()); + } else { + // could not delete file from file + // system + LOGGER.info("Image '" + imageid + "' konnte nicht gelöscht werden."); + + JOptionPane.showMessageDialog(null, "Image konnte nicht gelöscht werden.", "Fehler", + JOptionPane.INFORMATION_MESSAGE); + } + + } catch (TException e) { + + e.printStackTrace(); + JOptionPane.showMessageDialog(null, e.getCause() + "\n" + e.getStackTrace(), + "Debug-Message", JOptionPane.ERROR_MESSAGE); } } + }); btnDelete.setBounds(449, 508, 118, 23); contentPanel.add(btnDelete); diff --git a/dozentenmodul/src/main/java/gui/image/FTPCreateUploader_GUI.java b/dozentenmodul/src/main/java/gui/image/FTPCreateUploader_GUI.java index 6638de8c..ee0de205 100644 --- a/dozentenmodul/src/main/java/gui/image/FTPCreateUploader_GUI.java +++ b/dozentenmodul/src/main/java/gui/image/FTPCreateUploader_GUI.java @@ -12,9 +12,6 @@ import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; import javax.swing.JButton; import javax.swing.JFileChooser; @@ -40,7 +37,7 @@ import models.person; import org.apache.log4j.Logger; import org.apache.thrift.TException; -import org.openslx.sat.thrift.iface.User; +import org.openslx.sat.thrift.iface.TransferInformation; import org.openslx.thrifthelper.ThriftManager; import util.GuiManager; @@ -61,9 +58,7 @@ public class FTPCreateUploader_GUI extends JInternalFrame implements PropertyCha private JLabel lblPath; private JProgressBar progressBar; - private String host = SessionData.serverAdress; - private int port = 21; - private User user; + private final String host = SessionData.serverAdress; private File uploadFile; private UploadTask task; private JLabel lblUpSpeed; @@ -83,7 +78,7 @@ public class FTPCreateUploader_GUI extends JInternalFrame implements PropertyCha private int progress = 0; // progress of upload private boolean isCurrentlyLoading = false; // currently up or downloading file private boolean isAborted = false; // down- or upload was manually aborted - private String uuid; + private TransferInformation transferInfo = null; public static final String HELP_MESSAGE = "<html><div align = \"center\">" + "Laden Sie hier Ihre .vmdk-Datei hoch, die dann als virtuelles Labor geladen werden kann.<br />" @@ -99,40 +94,20 @@ public class FTPCreateUploader_GUI extends JInternalFrame implements PropertyCha final String[] options = { "Beenden", "Abbrechen" }; - try { - - uuid = ThriftManager.getSatClient().createRandomUUID(SessionData.authToken); - - } catch (TException e1) { - - e1.printStackTrace(); - } addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosing(InternalFrameEvent arg0) { if (taskrun == true) { // check if user wants to quit. - int choice = JOptionPane - .showOptionDialog( - null, - "Aktuell ist ein Upload aktiv. Wollen Sie diesen Abbrechen und das Programm beenden?", - "Upload aktiv", JOptionPane.YES_NO_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE, null, options, options[1]); + int choice = JOptionPane.showOptionDialog( + null, + "Aktuell ist ein Upload aktiv. Wollen Sie diesen Abbrechen und das Programm beenden?", + "Upload aktiv", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, + null, options, options[1]); // 0=beenden, 1=abbrechen if (choice == 0) { - try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName, SessionData.authToken); - } catch (TException e1) { - - e1.printStackTrace(); - } task.cancel(true); - try { - ThriftManager.getSatClient().setSessionInvalid(SessionData.authToken); - } catch (TException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + // TODO: Generic exit callback? System.exit(0); }// end if choice } @@ -278,8 +253,7 @@ public class FTPCreateUploader_GUI extends JInternalFrame implements PropertyCha panel.add(lblUploadIhresImage); JTextPane txtpnFhreSieBitte = new JTextPane(); - txtpnFhreSieBitte - .setText("Führen Sie bitte die folgenden 3 Schritte aus um Ihr Image auf unseren Server zu laden."); + txtpnFhreSieBitte.setText("Führen Sie bitte die folgenden 3 Schritte aus um Ihr Image auf unseren Server zu laden."); txtpnFhreSieBitte.setEditable(false); txtpnFhreSieBitte.setBackground(SystemColor.menu); txtpnFhreSieBitte.setBounds(10, 36, 509, 32); @@ -343,14 +317,7 @@ public class FTPCreateUploader_GUI extends JInternalFrame implements PropertyCha public void actionPerformed(ActionEvent e) { isAborted = true; // set flag - try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName, SessionData.authToken); - LOGGER.info("Deleted FTP user."); - } catch (TException e1) { - - e1.printStackTrace(); - } - task.cancel(true); + cancelUpload(); resetValues(); // reset buttons @@ -398,30 +365,18 @@ public class FTPCreateUploader_GUI extends JInternalFrame implements PropertyCha Config.store(); if (taskrun == true) { - try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName, - SessionData.authToken); - - } catch (TException e1) { - - e1.printStackTrace(); - JOptionPane.showMessageDialog(null, - e1.getCause() + "\n" + e1.getStackTrace(), "Debug-Message", - JOptionPane.ERROR_MESSAGE); - } - task.cancel(true); + cancelUpload(); } // Erstellung Array vom Datentyp Object, Hinzufügen der // Optionen Object[] options = { "Neue Veranstaltung erstellen", "Zum Hauptmenü zurückkehren" }; - int choice = JOptionPane - .showOptionDialog( - null, - "Möchten Sie eine neue Veranstaltung zu diesem Image erstellen oder in das Hauptmenü zurückkehren?", - "Alternativen", JOptionPane.DEFAULT_OPTION, - JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); + int choice = JOptionPane.showOptionDialog( + null, + "Möchten Sie eine neue Veranstaltung zu diesem Image erstellen oder in das Hauptmenü zurückkehren?", + "Alternativen", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, + null, options, options[0]); // 0=New Lecture, 1=Main Menu if (choice == 0) { @@ -442,24 +397,16 @@ public class FTPCreateUploader_GUI extends JInternalFrame implements PropertyCha JOptionPane.QUESTION_MESSAGE, null, options, options[1]); // 0=beenden, 1=abbrechen if (choice == 0) { - try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName, - SessionData.authToken); - } catch (TException e1) { - - e1.printStackTrace(); - } - task.cancel(true); + cancelUpload(); // not loading files, go back one page dispose(); }// end if choice } else { - int selectedOption = JOptionPane - .showConfirmDialog( - null, - "<html>Achtung: Alle Änderungen gehen verloren!<br />Klicken Sie auf fertigstellen, wenn Sie die Änderungen dauerhaft speichern möchten.<br /><br />Möchten Sie jetzt abbrechen und zurück?</html>", - "Abbrechen und zurück", JOptionPane.YES_NO_OPTION); + int selectedOption = JOptionPane.showConfirmDialog( + null, + "<html>Achtung: Alle Änderungen gehen verloren!<br />Klicken Sie auf fertigstellen, wenn Sie die Änderungen dauerhaft speichern möchten.<br /><br />Möchten Sie jetzt abbrechen und zurück?</html>", + "Abbrechen und zurück", JOptionPane.YES_NO_OPTION); if (selectedOption == JOptionPane.YES_OPTION) { GuiManager.show(new PermissionCreateImage_GUI()); } else { @@ -478,6 +425,16 @@ public class FTPCreateUploader_GUI extends JInternalFrame implements PropertyCha } + protected void cancelUpload() { + try { + ThriftManager.getSatClient().cancelUpload(transferInfo.token); + } catch (TException e1) { + // Don't care if it fails, will time out eventually.... + } + task.cancel(true); + transferInfo = null; + } + private void buttonUploadActionPerformed(ActionEvent event) { isAborted = false; @@ -486,22 +443,22 @@ public class FTPCreateUploader_GUI extends JInternalFrame implements PropertyCha btnUploadStarten.setText("Bitte warten"); try { - user = ThriftManager.getSatClient().getFtpUser(SessionData.authToken); + transferInfo = ThriftManager.getSatClient().requestUpload(SessionData.authToken, + uploadFile.length(), null); LOGGER.info("Received FTP user."); } catch (TException e) { - LOGGER.error("Konnte vom Satellit keinen FTP-User erhalten!"); + LOGGER.error("Konnte vom Satellit kein upload token erhalten!"); e.printStackTrace(); - JOptionPane.showMessageDialog(null, "Konnte vom Satellit keinen FTP-User erhalten!", + JOptionPane.showMessageDialog(null, "Konnte vom Satellit kein upload token erhalten!", "Debug-Message", JOptionPane.ERROR_MESSAGE); + transferInfo = null; + return; } - DateFormat formatter = new SimpleDateFormat("yyyMMddHHmmss"); - Image.NewName = formatter.format(new Date()) + "_" + person.verantwortlicher.getHochschule() + "_" - + person.verantwortlicher.getUsername() + "_" + Image.Imagename + ".vmdk"; LOGGER.info("Uploading to host: " + host); - task = new UploadTask(host, port, user.userName, user.password, user.path + "temp/", uploadFile); + task = new UploadTask(host, transferInfo.plainPort, transferInfo.token, uploadFile); task.addPropertyChangeListener(this); task.execute(); @@ -531,10 +488,8 @@ public class FTPCreateUploader_GUI extends JInternalFrame implements PropertyCha btnFinish.setEnabled(false); } - if ("speed" == arg0.getPropertyName()) { + if ("speed".equals(arg0.getPropertyName())) { speed = (double) arg0.getNewValue(); - // if(speed<=1){ - lblUpSpeed.setText(String.format("%.2f", speed) + " MB/s"); } @@ -543,8 +498,8 @@ public class FTPCreateUploader_GUI extends JInternalFrame implements PropertyCha lblFertig.setText((bytesread / 1024 / 1024) + " MB"); lblVerbleibend.setText(((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) + " MB"); - lblZeit.setText(String - .valueOf(((((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) / speed) / 60) + 1) + lblZeit.setText(String.valueOf( + ((((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) / speed) / 60) + 1) .substring( 0, String.valueOf( @@ -565,21 +520,21 @@ public class FTPCreateUploader_GUI extends JInternalFrame implements PropertyCha try { - ThriftManager.getSatClient().writeVLdata(Image.Imagename, Image.Desc, - person.verantwortlicher.getTel(), person.verantwortlicher.getFakultaet(), Image.Licensed, - Image.Internet, Image.Ram, Image.Cpu, "temp/" + Image.NewName, Image.Vorlage, - Image.Filesize, Image.ShareMode, Image.OS, uuid, SessionData.authToken, - person.verantwortlicher.getUserID()); + Image.ImageId = ThriftManager.getSatClient().finishImageUpload(Image.Imagename, Image.Desc, + Image.Licensed, Image.Internet, Image.Filesize, Image.ShareMode, Image.OS, + transferInfo.token); - System.out.println("starting file copy..."); - ThriftManager.getSatClient().startFileCopy(Image.NewName, SessionData.authToken); + if (Image.ImageId == null) { + // Should never happen, but let's handle it + throw new TException("no image id returned"); + } - ThriftManager.getSatClient().writeImageRights(uuid, SessionData.authToken, + ThriftManager.getSatClient().writeImageRights(Image.ImageId, SessionData.authToken, person.verantwortlicher.getRole(), person.verantwortlicher.getHochschule(), person.verantwortlicher.getUserID()); for (int i = 0; i < RightsManagement.rightsManagement.getPermittedUserList().size(); i++) { - ThriftManager.getSatClient().writeAdditionalImageRights(uuid, + ThriftManager.getSatClient().writeAdditionalImageRights(Image.ImageId, RightsManagement.rightsManagement.getPermittedUserList().get(i).getUserID(), RightsManagement.rightsManagement.getPermittedUserList().get(i).isImageRead(), RightsManagement.rightsManagement.getPermittedUserList().get(i).isImageWrite(), diff --git a/dozentenmodul/src/main/java/gui/image/FTPEditDownloader_GUI.java b/dozentenmodul/src/main/java/gui/image/FTPEditDownloader_GUI.java index b7b0a9f4..11aed0f9 100644 --- a/dozentenmodul/src/main/java/gui/image/FTPEditDownloader_GUI.java +++ b/dozentenmodul/src/main/java/gui/image/FTPEditDownloader_GUI.java @@ -36,7 +36,7 @@ import models.person; import org.apache.log4j.Logger; import org.apache.thrift.TException; -import org.openslx.sat.thrift.iface.User; +import org.openslx.sat.thrift.iface.TransferInformation; import org.openslx.thrifthelper.ThriftManager; import util.GuiManager; @@ -46,23 +46,18 @@ import ftp.DownloadTask; import gui.intro.MainMenue_GUI; @SuppressWarnings("serial") -public class FTPEditDownloader_GUI extends JInternalFrame implements - PropertyChangeListener { +public class FTPEditDownloader_GUI extends JInternalFrame implements PropertyChangeListener { /** * Logger instance for this class. */ - private final static Logger LOGGER = Logger - .getLogger(FTPEditDownloader_GUI.class); - + private final static Logger LOGGER = Logger.getLogger(FTPEditDownloader_GUI.class); + private final JPanel contentPanel = new JPanel(); private JLabel lblPath; private JLabel lblDownSpeed; - private User user; private JProgressBar progressBar; private String host = SessionData.serverAdress; - private int port = 21; - private String downloadFile = ""; private DownloadTask task; private JLabel lblFertig; private JLabel lblFilesize; @@ -78,9 +73,9 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements private JButton btnDownloadStarten = new JButton("Download starten"); private JButton btnDownloadStoppen = new JButton("Download abbrechen"); private JLabel lblAnleitung; - private boolean isCurrentlyLoading = false; // currently up or downloading - // file + private boolean isCurrentlyLoading = false; // currently up or downloading file private boolean isAborted = false; // down- or upload was manually aborted + private TransferInformation transferInfo = null; public static final String HELP_MESSAGE = "<html><div align=\"center\">" + "Hier können Sie Images herunterladen.<br />" + "Klicken Sie anschließend auf \"Zurück\", um zu Ihrer vorherigen Auswahl zurückzugelangen.<br />" @@ -91,34 +86,25 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements */ public FTPEditDownloader_GUI() { + final String[] options = { "Beenden", "Abbrechen" }; - final Object[] options = { "Beenden", "Abbrechen" }; addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosing(InternalFrameEvent arg0) { if (taskrun == true) { // check if user wants to quit. - int choice = JOptionPane - .showOptionDialog( - null, - "Aktuell ist ein Download aktiv. Wollen Sie diesen Abbrechen und das Programm beenden?", - "Upload aktiv", - JOptionPane.YES_NO_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE, null, - options, options[1]); + int choice = JOptionPane.showOptionDialog( + null, + "Aktuell ist ein Download aktiv. Wollen Sie diesen Abbrechen und das Programm beenden?", + "Upload aktiv", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, + null, options, options[1]); // 0=beenden, 1=abbrechen if (choice == 0) { try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName,SessionData.authToken); - try { - ThriftManager.getSatClient().setSessionInvalid(SessionData.authToken); - } catch (TException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } + ThriftManager.getSatClient().cancelDownload(transferInfo.token); + ThriftManager.getSatClient().setSessionInvalid(SessionData.authToken); } catch (TException e1) { - - e1.printStackTrace(); + LOGGER.error("Error cancelling download..", e1); } task.cancel(true); System.exit(0); @@ -129,7 +115,7 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements setResizable(false); setBackground(Color.WHITE); - setTitle("Dozentenmodul - Image herunterladen - "+person.verantwortlicher.getUserID()); + setTitle("Dozentenmodul - Image herunterladen - " + person.verantwortlicher.getUserID()); // Aktion die beim Schliessen durchgefuehrt werden soll setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); @@ -141,9 +127,9 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); { - JButton btnSpeicherortAuswhlen = new JButton( - "Speicherort auswählen"); + JButton btnSpeicherortAuswhlen = new JButton("Speicherort auswählen"); btnSpeicherortAuswhlen.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent arg0) { fc = new JFileChooser(Config.getLastDownloadPath()); @@ -174,6 +160,7 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements lblPath.setText(Config.getLastDownloadPath()); lblPath.addPropertyChangeListener(new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent arg0) { if (lblPath.getText().trim().isEmpty()) { // wenn leer, dann upload button nicht freigeben @@ -191,6 +178,7 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements btnDownloadStarten.setEnabled(false); btnDownloadStarten.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent arg0) { buttonDownloadActionPerformed(arg0); } @@ -205,8 +193,7 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements progressBar.setBounds(102, 234, 485, 30); contentPanel.add(progressBar); - JLabel lblDownloadgeschwindigkeit = new JLabel( - "Downloadgeschwindigkeit:"); + JLabel lblDownloadgeschwindigkeit = new JLabel("Downloadgeschwindigkeit:"); lblDownloadgeschwindigkeit.setBounds(102, 275, 141, 14); contentPanel.add(lblDownloadgeschwindigkeit); @@ -238,8 +225,7 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements lblVerbleibend.setBounds(183, 350, 108, 14); contentPanel.add(lblVerbleibend); - JLabel lblGeschtzteVerbleibendeZeit = new JLabel( - "Geschätzte Verbleibende Zeit:"); + JLabel lblGeschtzteVerbleibendeZeit = new JLabel("Geschätzte Verbleibende Zeit:"); lblGeschtzteVerbleibendeZeit.setBounds(102, 300, 150, 14); contentPanel.add(lblGeschtzteVerbleibendeZeit); @@ -259,8 +245,7 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements panel.add(lblImageDownloader); JTextPane txtpnWhlenSieEinen = new JTextPane(); - txtpnWhlenSieEinen - .setText("Wählen Sie einen Ort aus, um das von Ihnen gewählte Image herunterzuladen."); + txtpnWhlenSieEinen.setText("Wählen Sie einen Ort aus, um das von Ihnen gewählte Image herunterzuladen."); txtpnWhlenSieEinen.setEditable(false); txtpnWhlenSieEinen.setBackground(SystemColor.menu); txtpnWhlenSieEinen.setBounds(10, 36, 509, 32); @@ -323,7 +308,6 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements menuBar.setBounds(0, 0, 597, 21); contentPanel.add(menuBar); - lblAnleitung = new JLabel( "<HTML><U>Anleitung zum Erstellen einer virtuellen Maschine herunterladen</U></HTML>"); lblAnleitung.setForeground(Color.BLUE); @@ -336,15 +320,13 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements lblAnleitung.setBounds(102, 448, 311, 14); contentPanel.add(lblAnleitung); btnDownloadStoppen.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { isAborted = true; // set flag try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName,SessionData.authToken); - LOGGER.info("FTP user deleted."); + ThriftManager.getSatClient().cancelDownload(transferInfo.token); } catch (TException e1) { - - e1.printStackTrace(); } task.cancel(true); resetValues(); @@ -364,25 +346,20 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements getContentPane().add(buttonPane, BorderLayout.SOUTH); { btnZurck.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { // check if loading file or not if (isCurrentlyLoading() == true) { - int choice = JOptionPane - .showOptionDialog( - null, - "Nicht abgeschlossene Uploads werden beendet. Trotzdem zurück gehen?", - "Warnung", - JOptionPane.YES_NO_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE, null, - options, options[1]); + int choice = JOptionPane.showOptionDialog(null, + "Nicht abgeschlossene Uploads werden beendet. Trotzdem zurück gehen?", + "Warnung", JOptionPane.YES_NO_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE, null, options, options[1]); // 0=beenden, 1=abbrechen if (choice == 0) { task.cancel(true); try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName,SessionData.authToken); + ThriftManager.getSatClient().cancelDownload(transferInfo.token); } catch (TException e1) { - - e1.printStackTrace(); } // go back one page @@ -400,8 +377,7 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements if (f.isDirectory()) { Config.setLastDownloadPath(f.toString()); } else if (f.getParentFile().isDirectory()) { - Config.setLastDownloadPath(f.getParentFile() - .toString()); + Config.setLastDownloadPath(f.getParentFile().toString()); } Config.store(); @@ -413,7 +389,6 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements } setVisible(true); - } private void buttonDownloadActionPerformed(ActionEvent event) { @@ -424,88 +399,70 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements // Klick btnDownloadStarten.setText("Bitte warten"); try { - user = ThriftManager.getSatClient().getFtpUser(SessionData.authToken); - - downloadFile = user.path - + "/" - + ThriftManager.getSatClient().getPathOfImage(Image.ImageId, - Image.Version,SessionData.authToken); - + transferInfo = ThriftManager.getSatClient().requestDownload(SessionData.authToken, Image.ImageId); } catch (TException e) { - - e.printStackTrace(); - JOptionPane.showMessageDialog(null, - e.getCause() + "\n" + e.getStackTrace(), "Debug-Message", + transferInfo = null; + JOptionPane.showMessageDialog(null, e.getCause() + "\n" + e.getStackTrace(), "Debug-Message", JOptionPane.ERROR_MESSAGE); } - task = new DownloadTask(host, port, user.userName, user.password, - downloadFile, lblPath.getText().trim().trim()); + task = new DownloadTask(host, transferInfo.plainPort, transferInfo.token, lblPath.getText().trim(), Image.Filesize); task.addPropertyChangeListener(this); task.execute(); taskrun = true; } + @Override public void propertyChange(PropertyChangeEvent arg0) { - if (isAborted == false) { - progress = 0; - if ("progress" == arg0.getPropertyName()) { - progress = (Integer) arg0.getNewValue(); - progressBar.setValue(progress); - } + if (isAborted) + return; + progress = 0; + if ("progress".equals(arg0.getPropertyName())) { + progress = (Integer) arg0.getNewValue(); + progressBar.setValue(progress); + } - if ("speed" == arg0.getPropertyName()) { - speed = (double) arg0.getNewValue(); + if ("speed".equals(arg0.getPropertyName())) { + speed = (double) arg0.getNewValue(); + lblDownSpeed.setText(String.format("%.2f", speed) + " MB/s"); + } - lblDownSpeed.setText(String.valueOf(speed).substring(0, - String.valueOf(speed).lastIndexOf(".") + 3) - + " MB/s"); - } + // Button zum Fertigstellen freischalten, wenn 100% erreicht sind + if (isCurrentlyLoading() == false || progressBar.getPercentComplete() == 1.0) { + // no download + btnDownloadStoppen.setEnabled(false); + } else { + // currently uploading, don't let user interact + btnDownloadStoppen.setEnabled(true); + } - // Button zum Fertigstellen freischalten, wenn 100% erreicht sind - if (isCurrentlyLoading() == false - || progressBar.getPercentComplete() == 1.0) { - // no download - btnDownloadStoppen.setEnabled(false); - } else { - // currently uploading, don't let user interact - btnDownloadStoppen.setEnabled(true); - } + if (arg0.getPropertyName().equals("bytesread")) { + bytesread = (long) arg0.getNewValue(); + lblFertig.setText((bytesread / 1024 / 1024) + " MB"); + lblVerbleibend.setText(((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) + " MB"); - if (arg0.getPropertyName().equals("bytesread")) { - bytesread = (long) arg0.getNewValue(); - lblFertig.setText((bytesread / 1024 / 1024) + " MB"); - lblVerbleibend - .setText(((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) - + " MB"); - - lblZeit.setText(String - .valueOf( - ((((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) / speed) / 60) + 1) - .substring( - 0, - String.valueOf( - (((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) / speed) / 60) - .lastIndexOf(".")) - + " Minuten"); + lblZeit.setText(String.valueOf( + ((((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) / speed) / 60) + 1).substring( + 0, + String.valueOf((((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) / speed) / 60) + .lastIndexOf(".")) + + " Minuten"); - } - if (arg0.getPropertyName().equals("filesize")) { - filesize = (long) arg0.getNewValue(); - lblFilesize.setText((filesize / 1024 / 1024) + " MB"); + } + if (arg0.getPropertyName().equals("filesize")) { + filesize = (long) arg0.getNewValue(); + lblFilesize.setText((filesize / 1024 / 1024) + " MB"); - } - }// end if + } }// end PropertyChange() - public boolean isCurrentlyLoading() { + private boolean isCurrentlyLoading() { isCurrentlyLoading = false; - if (lblVerbleibend.getText().trim().equals("0 MB") - || lblVerbleibend.getText().trim().equals("0")) { + if (lblVerbleibend.getText().trim().equals("0 MB") || lblVerbleibend.getText().trim().equals("0")) { isCurrentlyLoading = false; } else { isCurrentlyLoading = true; @@ -513,7 +470,7 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements return isCurrentlyLoading; }// end isCurrentlyLoading() - public void resetValues() { + private void resetValues() { lblDownSpeed.setText("0"); lblZeit.setText("0"); lblFertig.setText("0"); @@ -522,7 +479,7 @@ public class FTPEditDownloader_GUI extends JInternalFrame implements progressBar.setValue(0); }// end resetValues - public void resetButtons() { + private void resetButtons() { btnDownloadStarten.setEnabled(true); btnDownloadStarten.setText("Download starten"); btnDownloadStoppen.setEnabled(false); diff --git a/dozentenmodul/src/main/java/gui/image/FTPEditUploader_GUI.java b/dozentenmodul/src/main/java/gui/image/FTPEditUploader_GUI.java index 7777bf37..27f3d7ce 100644 --- a/dozentenmodul/src/main/java/gui/image/FTPEditUploader_GUI.java +++ b/dozentenmodul/src/main/java/gui/image/FTPEditUploader_GUI.java @@ -12,9 +12,6 @@ import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; import javax.swing.JButton; import javax.swing.JFileChooser; @@ -40,10 +37,11 @@ import models.person; import org.apache.log4j.Logger; import org.apache.thrift.TException; -import org.openslx.sat.thrift.iface.User; +import org.openslx.sat.thrift.iface.TransferInformation; import org.openslx.thrifthelper.ThriftManager; import util.GuiManager; +import util.MessageType; import config.Config; import ftp.UploadTask; import gui.intro.MainMenue_GUI; @@ -60,10 +58,8 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang private JLabel lblPath; private JProgressBar progressBar; private String host = SessionData.serverAdress; - private int port = 21; - private User user; private File uploadFile; - private UploadTask task; + private UploadTask task = null; private JLabel lblUpSpeed; private JLabel lblFertig; private JLabel lblFilesize; @@ -73,16 +69,14 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang private long filesize; private double speed; private long bytesread; - private boolean fileupload = false; - private boolean taskrun = false; private int progress = 0; private JButton btnUploadStarten = new JButton("Upload auf Server starten"); private JButton btnSpeicherortAuswhlen = new JButton("Image auswählen"); private JButton btnFinish = new JButton("Fertigstellen"); private JButton btnZurck = new JButton("Zurück"); private JButton btnUploadStoppen = new JButton("Upload abbrechen"); - private boolean isCurrentlyLoading = false; // currently up or downloading - // file + private TransferInformation transferInfo = null; + // file private boolean isAborted = false; // down- or upload was manually aborted public static final String HELP_MESSAGE = "<html><div align = \"center\">" + "Laden Sie hier Ihre bearbeitete .vmdk-Datei hoch, die dann als virtuelles Labor geladen werden kann.<br />" @@ -96,41 +90,28 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang */ public FTPEditUploader_GUI() { - final Object[] options = { "Beenden", "Abbrechen" }; + final String[] options = { "Beenden", "Abbrechen" }; addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosing(InternalFrameEvent arg0) { - if (taskrun == true) { - // check if user wants to quit. - int choice = JOptionPane - .showOptionDialog( - null, - "Aktuell ist ein Upload aktiv. Wollen Sie diesen Abbrechen und das Programm beenden?", - "Upload aktiv", JOptionPane.YES_NO_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE, null, options, options[1]); - // 0=beenden, 1=abbrechen - if (choice == 0) { - try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName, SessionData.authToken); - } catch (TException e1) { - e1.printStackTrace(); - } - task.cancel(true); - try { - ThriftManager.getSatClient().setSessionInvalid(SessionData.authToken); - } catch (TException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - try { - ThriftManager.getSatClient().setSessionInvalid(SessionData.authToken); - } catch (TException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - System.exit(0); - }// end if choice - } + if (!isCurrentlyLoading()) + return; + // check if user wants to quit. + int choice = JOptionPane.showOptionDialog( + null, + "Aktuell ist ein Upload aktiv. Wollen Sie diesen Abbrechen und das Programm beenden?", + "Upload aktiv", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, + options, options[1]); + // 0=beenden, 1=abbrechen + if (choice == 0) { + try { + ThriftManager.getSatClient().cancelDownload(transferInfo.token); + ThriftManager.getSatClient().setSessionInvalid(SessionData.authToken); + } catch (TException e1) { + } + task.cancel(true); + System.exit(0); + }// end if choice } }); setResizable(false); @@ -264,8 +245,7 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang panel.add(lblUploadIhresImage); JTextPane txtpnFhreSieBitte = new JTextPane(); - txtpnFhreSieBitte - .setText("Laden Sie optional ein neues Image hoch, oder klicken Sie direkt auf \"Fertigstellen\", um reine Änderungen der Angaben direkt zu übernehmen."); + txtpnFhreSieBitte.setText("Laden Sie optional ein neues Image hoch, oder klicken Sie direkt auf \"Fertigstellen\", um reine Änderungen der Angaben direkt zu übernehmen."); txtpnFhreSieBitte.setEditable(false); txtpnFhreSieBitte.setBackground(SystemColor.menu); txtpnFhreSieBitte.setBounds(10, 36, 509, 42); @@ -327,10 +307,8 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang isAborted = true; // set flag try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName, SessionData.authToken); - LOGGER.info("FTP user deleted."); + ThriftManager.getSatClient().cancelDownload(transferInfo.token); } catch (TException e1) { - e1.printStackTrace(); } task.cancel(true); resetValues(); @@ -365,19 +343,11 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang // save data boolean success = updateData(); - if (success == true) { - LOGGER.info("Bearbeitetes Image '" + Image.Imagename - + "' erfolgreich gespeichert."); - JOptionPane.showMessageDialog(null, - "Die Änderungen wurden erfolgreich gespeichert.", - "Änderungen gespeichert", JOptionPane.INFORMATION_MESSAGE); - } else { - LOGGER.error("Bearbeitetes Image '" + Image.Imagename - + "' konnte nicht gespeichert werden."); - JOptionPane.showMessageDialog(null, - "Die Änderungen konnten nicht gespeichert werden.", "Fehler", - JOptionPane.ERROR_MESSAGE); - } + if (!success) + return; + LOGGER.info("Bearbeitetes Image '" + Image.Imagename + "' erfolgreich gespeichert."); + JOptionPane.showMessageDialog(null, "Die Änderungen wurden erfolgreich gespeichert.", + "Änderungen gespeichert", JOptionPane.INFORMATION_MESSAGE); if (lblPath.getText().trim().length() > 0) { File f = new File(lblPath.getText().trim()); @@ -393,17 +363,7 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang GuiManager.show(new MainMenue_GUI()); - if (taskrun == true) { - try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName, - SessionData.authToken); - - } catch (TException e1) { - e1.printStackTrace(); - JOptionPane.showMessageDialog(null, - e1.getCause() + "\n" + e1.getStackTrace(), "Debug-Message", - JOptionPane.ERROR_MESSAGE); - } + if (isCurrentlyLoading()) { task.cancel(true); } @@ -421,8 +381,7 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang // 0=beenden, 1=abbrechen if (choice == 0) { try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName, - SessionData.authToken); + ThriftManager.getSatClient().cancelDownload(transferInfo.token); } catch (TException e1) { e1.printStackTrace(); } @@ -449,11 +408,10 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang }// end if coice } else { - int selectedOption = JOptionPane - .showConfirmDialog( - null, - "<html>Achtung: Alle Änderungen gehen verloren!<br />Klicken Sie auf fertigstellen, wenn Sie die Änderungen dauerhaft speichern möchten.<br /><br />Möchten Sie jetzt abbrechen und zurück?</html>", - "Abbrechen und zurück", JOptionPane.YES_NO_OPTION); + int selectedOption = JOptionPane.showConfirmDialog( + null, + "<html>Achtung: Alle Änderungen gehen verloren!<br />Klicken Sie auf fertigstellen, wenn Sie die Änderungen dauerhaft speichern möchten.<br /><br />Möchten Sie jetzt abbrechen und zurück?</html>", + "Abbrechen und zurück", JOptionPane.YES_NO_OPTION); if (selectedOption == JOptionPane.YES_OPTION) { try { System.out.println("userID in editimageuploader is : " @@ -491,31 +449,23 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang private void buttonUploadActionPerformed(ActionEvent event) { isAborted = false; - fileupload = true; progressBar.setValue(0); - btnUploadStarten.setEnabled(false); // verhindert einen weiteren klick + btnUploadStarten.setEnabled(false); // verhindert einen weiteren Klick btnUploadStarten.setText("Bitte warten"); try { - user = ThriftManager.getSatClient().getFtpUser(SessionData.authToken); - LOGGER.info("Received FTP user."); + transferInfo = ThriftManager.getSatClient().requestUpload(SessionData.authToken, + uploadFile.length(), null); } catch (TException e) { - e.printStackTrace(); + transferInfo = null; JOptionPane.showMessageDialog(null, "Konnte vom Satelliten keine FTP-User erhalten!", "Debug-Message", JOptionPane.ERROR_MESSAGE); } - DateFormat formatter = new SimpleDateFormat("yyyMMddHHmmss"); - - // set new file name and path only when uploading a new file. else use - // old filename and path - Image.NewName = formatter.format(new Date()) + "_" + person.verantwortlicher.getHochschule() + "_" - + person.verantwortlicher.getUsername() + "_" + Image.Imagename + ".vmdk"; - task = new UploadTask(host, port, user.userName, user.password, user.path + "temp/", uploadFile); + task = new UploadTask(host, transferInfo.plainPort, transferInfo.token, uploadFile); task.addPropertyChangeListener(this); task.execute(); - taskrun = true; } @@ -523,7 +473,7 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang if (isAborted == false) { // set progressbar - if ("progress" == arg0.getPropertyName()) { + if ("progress".equals(arg0.getPropertyName())) { progress = (Integer) arg0.getNewValue(); progressBar.setValue(progress); } @@ -540,22 +490,20 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang btnFinish.setEnabled(false); } - if ("speed" == arg0.getPropertyName()) { + if ("speed".equals(arg0.getPropertyName())) { speed = (double) arg0.getNewValue(); // if(speed<=1){ - lblUpSpeed.setText(String.valueOf(speed).substring(0, - String.valueOf(speed).lastIndexOf(".") + 3) - + " MB/s"); + lblUpSpeed.setText(String.format("%.2f", speed) + " MB/s"); } - if ("bytesread" == arg0.getPropertyName()) { + if ("bytesread".equals(arg0.getPropertyName())) { bytesread = (long) arg0.getNewValue(); lblFertig.setText((bytesread / 1024 / 1024) + " MB"); lblVerbleibend.setText(((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) + " MB"); - lblZeit.setText(String - .valueOf(((((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) / speed) / 60) + 1) + lblZeit.setText(String.valueOf( + ((((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) / speed) / 60) + 1) .substring( 0, String.valueOf( @@ -564,7 +512,7 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang + " Minuten"); } - if ("filesize" == arg0.getPropertyName()) { + if ("filesize".equals(arg0.getPropertyName())) { filesize = (long) arg0.getNewValue(); lblFilesize.setText((filesize / 1024 / 1024) + " MB"); @@ -573,84 +521,90 @@ public class FTPEditUploader_GUI extends JInternalFrame implements PropertyChang }// end propertyChange public boolean updateData() { - - try { - //if a new file has been uploaded and new filename is set - if (Image.NewName != null) { - LOGGER.debug("New file uploaded and new filename is set"); - - ThriftManager.getSatClient().updateImageData(Image.Imagename, Image.Imagename, - Image.Desc, - //Image.Imagepath, - "temp/" + Image.NewName, Image.Licensed, Image.Internet, Image.Ram, Image.Cpu, - Image.ImageId, Image.Version, Image.Vorlage, Image.Filesize, Image.ShareMode, - Image.OS, SessionData.authToken); - if (fileupload == true) { - ThriftManager.getSatClient().startFileCopy(Image.NewName, SessionData.authToken); - } - - } else { //no new file uploaded and old file name stays - LOGGER.debug("old file should remain"); - - ThriftManager.getSatClient().updateImageData(Image.Imagename, Image.Imagename, - Image.Desc, - //"temp/" + Image.NewName, //wrong - Image.Imagepath, Image.Licensed, Image.Internet, Image.Ram, Image.Cpu, Image.ImageId, - Image.Version, Image.Vorlage, Image.Filesize, Image.ShareMode, Image.OS, - SessionData.authToken); - - if (fileupload == true) { - ThriftManager.getSatClient().startFileCopy(Image.NewName, SessionData.authToken); - // client.startFileCopy(Image.Imagename); - } + if (isCurrentlyLoading()) { + JOptionPane.showMessageDialog(null, "Vorgang noch nicht abgeschlossen!!", "Fehler", + JOptionPane.ERROR_MESSAGE); + return false; + } + boolean ret; + Exception ex; + //if a new file has been uploaded and new filename is set + if (task != null && task.isDone()) { + LOGGER.debug("New file uploaded, updating DB entry..."); + + ret = false; + ex = null; + try { + ret = ThriftManager.getSatClient().updateImageFile(transferInfo.token, Image.ImageId); + } catch (Exception e) { + ex = e; + } + if (!ret) { + GuiManager.showMessageBox( + "Die Metadaten des Images konnten nicht auf das neue Image umgeschrieben werden.", + MessageType.ERROR, LOGGER, ex); + return false; } + } - // remove all additional user permissions on first stage + LOGGER.debug("old file should remain"); + ret = false; + ex = null; + try { + ret = ThriftManager.getSatClient().updateImageData(SessionData.authToken, Image.ImageId, + Image.Imagename, Image.Desc, Image.Licensed, Image.Internet, Image.ShareMode, Image.OS); + } catch (TException e) { + ex = e; + } + if (!ret) { + GuiManager.showMessageBox("Serverseitiger Fehler beim Aktualisieren der Metadaten", + MessageType.ERROR, LOGGER, ex); + return false; + } + + // remove all additional user permissions on first stage + ret = false; + ex = null; + try { ThriftManager.getSatClient().deleteAllAdditionalImagePermissions(Image.ImageId, SessionData.authToken, person.verantwortlicher.getUserID()); + } catch (TException e) { + ex = e; + } + if (ex != null) { + GuiManager.showMessageBox("Konnte alte Permissions nicht aus der Datenbank entfernen.", + MessageType.WARNING, LOGGER, ex); + } - // then, add user permissions as they have been set new - for (int i = 0; i < RightsManagement.rightsManagement.getPermittedUserList().size(); i++) { - /*System.out.println("Writing additional rights for user " - + RightsManagement.rightsManagement - .getPermittedUserList().get(i).getUserID() - + ", User " - + i - + "/" - + RightsManagement.rightsManagement.getPermittedUserList().size()); - */ - - ThriftManager.getSatClient().writeAdditionalImageRights(Image.ImageId, + // then, add user permissions as they have been set new + ret = true; // (sic) + ex = null; + for (int i = 0; i < RightsManagement.rightsManagement.getPermittedUserList().size(); i++) { + try { + ret = ThriftManager.getSatClient().writeAdditionalImageRights(Image.ImageId, RightsManagement.rightsManagement.getPermittedUserList().get(i).getUserID(), RightsManagement.rightsManagement.getPermittedUserList().get(i).isImageRead(), RightsManagement.rightsManagement.getPermittedUserList().get(i).isImageWrite(), RightsManagement.rightsManagement.getPermittedUserList().get(i).isImageLinkAllowed(), RightsManagement.rightsManagement.getPermittedUserList().get(i).isImageAdmin(), - SessionData.authToken); - - }// end for - - } catch (TException e) { - e.printStackTrace(); - JOptionPane.showMessageDialog(null, - "Konnte die Metadaten des Images nicht in die Datenbank speichern!", "Debug-Message", - JOptionPane.ERROR_MESSAGE); - return false; + SessionData.authToken) + && ret; + } catch (TException e) { + ex = e; + } + }// end for + if (!ret) { + GuiManager.showMessageBox("Serverseitiger Fehler beim Schreiben der neuen Berechtigungen.", + MessageType.WARNING, LOGGER, ex); } + return true; } public boolean isCurrentlyLoading() { - isCurrentlyLoading = false; - - if (lblVerbleibend.getText().trim().equals("0 MB") || lblVerbleibend.getText().trim().equals("0")) { - isCurrentlyLoading = false; - } else { - isCurrentlyLoading = true; - } - return isCurrentlyLoading; + return task != null && !task.isDone(); }// end isCurrentlyLoading() public void resetValues() { diff --git a/dozentenmodul/src/main/java/gui/image/FTPSearchDownloader_GUI.java b/dozentenmodul/src/main/java/gui/image/FTPSearchDownloader_GUI.java index f92d6a5c..c4b79d0d 100644 --- a/dozentenmodul/src/main/java/gui/image/FTPSearchDownloader_GUI.java +++ b/dozentenmodul/src/main/java/gui/image/FTPSearchDownloader_GUI.java @@ -35,10 +35,11 @@ import models.person; import org.apache.log4j.Logger; import org.apache.thrift.TException; -import org.openslx.sat.thrift.iface.User; +import org.openslx.sat.thrift.iface.TransferInformation; import org.openslx.thrifthelper.ThriftManager; import util.GuiManager; +import util.MessageType; import util.OpenLinks; import config.Config; import ftp.DownloadTask; @@ -52,11 +53,8 @@ public class FTPSearchDownloader_GUI extends JInternalFrame implements PropertyC private final JPanel contentPanel = new JPanel(); private JLabel lblPath; private JLabel lblDownSpeed; - private User user; private JProgressBar progressBar; private String host = SessionData.serverAdress; - private int port = 21; - private String downloadFile = ""; private DownloadTask task; private JLabel lblFertig; private JLabel lblFilesize; @@ -73,9 +71,8 @@ public class FTPSearchDownloader_GUI extends JInternalFrame implements PropertyC private JButton btnMainMenu = new JButton("Hauptmenü"); private JButton btnDownloadStoppen = new JButton("Download abbrechen"); private JLabel lblAnleitung; - private boolean isCurrentlyLoading = false; // currently up or downloading - // file private boolean isAborted = false; // down- or upload was manually aborted + private TransferInformation transferInfo = null; public static final String HELP_MESSAGE = "<html><div align=\"center\">" + "Hier können Sie Images herunterladen.<br />" + "Klicken Sie anschließend auf \"Zurück\" oder \"Hauptmenü\", um zu Ihrer vorherigen Auswahl oder zum Menü zurückzugelangen.<br />" @@ -92,32 +89,18 @@ public class FTPSearchDownloader_GUI extends JInternalFrame implements PropertyC public void internalFrameClosing(InternalFrameEvent arg0) { if (taskrun == true) { // check if user wants to quit. - int choice = JOptionPane - .showOptionDialog( - null, - "Aktuell ist ein Download aktiv. Wollen Sie diesen Abbrechen und das Programm beenden?", - "Upload aktiv", JOptionPane.YES_NO_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE, null, options, options[1]); + int choice = JOptionPane.showOptionDialog( + null, + "Aktuell ist ein Download aktiv. Wollen Sie diesen Abbrechen und das Programm beenden?", + "Upload aktiv", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, + null, options, options[1]); // 0=beenden, 1=abbrechen if (choice == 0) { try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName, SessionData.authToken); - try { - ThriftManager.getSatClient().setSessionInvalid(SessionData.authToken); - } catch (TException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - try { - ThriftManager.getSatClient().setSessionInvalid(SessionData.authToken); - } catch (TException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } + ThriftManager.getSatClient().cancelDownload(transferInfo.token); + ThriftManager.getSatClient().setSessionInvalid(SessionData.authToken); } catch (TException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); } task.cancel(true); @@ -324,11 +307,8 @@ public class FTPSearchDownloader_GUI extends JInternalFrame implements PropertyC isAborted = true; // set flag try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName, SessionData.authToken); - LOGGER.info("Deleted FTP user."); + ThriftManager.getSatClient().cancelDownload(transferInfo.token); } catch (TException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); } task.cancel(true); resetValues(); @@ -360,11 +340,8 @@ public class FTPSearchDownloader_GUI extends JInternalFrame implements PropertyC if (choice == 0) { task.cancel(true); try { - ThriftManager.getSatClient().DeleteFtpUser(user.userName, - SessionData.authToken); + ThriftManager.getSatClient().cancelDownload(transferInfo.token); } catch (TException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); } // go back one page GuiManager.show(new SearchImage_GUI()); @@ -401,26 +378,18 @@ public class FTPSearchDownloader_GUI extends JInternalFrame implements PropertyC isAborted = false; progressBar.setValue(0); - btnDownloadStarten.setEnabled(false); // verhindert schnellen zweiten - // Klick + btnDownloadStarten.setEnabled(false); // verhindert schnellen zweiten Klick btnDownloadStarten.setText("Bitte warten"); try { - user = ThriftManager.getSatClient().getFtpUser(SessionData.authToken); - - downloadFile = user.path - + "/" - + ThriftManager.getSatClient().getPathOfImage(Image.ImageId, - Image.Version, SessionData.authToken); - + transferInfo = ThriftManager.getSatClient().requestDownload(SessionData.authToken, Image.ImageId); } catch (TException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - JOptionPane.showMessageDialog(null, e.getCause() + "\n" + e.getStackTrace(), "Debug-Message", - JOptionPane.ERROR_MESSAGE); + transferInfo = null; + GuiManager.showMessageBox("Satellit verweigert den Download", MessageType.ERROR, LOGGER, e); + return; } - task = new DownloadTask(host, port, user.userName, user.password, downloadFile, lblPath.getText() - .trim()); + task = new DownloadTask(host, transferInfo.plainPort, transferInfo.token, lblPath.getText(), + Image.Filesize); task.addPropertyChangeListener(this); task.execute(); taskrun = true; @@ -462,8 +431,8 @@ public class FTPSearchDownloader_GUI extends JInternalFrame implements PropertyC lblFertig.setText((bytesread / 1024 / 1024) + " MB"); lblVerbleibend.setText(((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) + " MB"); - lblZeit.setText(String - .valueOf(((((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) / speed) / 60) + 1) + lblZeit.setText(String.valueOf( + ((((filesize / 1024 / 1024) - (bytesread / 1024 / 1024)) / speed) / 60) + 1) .substring( 0, String.valueOf( @@ -480,15 +449,8 @@ public class FTPSearchDownloader_GUI extends JInternalFrame implements PropertyC }// end if }// end propertyChange - public boolean isCurrentlyLoading() { - isCurrentlyLoading = false; - - if (lblVerbleibend.getText().trim().equals("0 MB") || lblVerbleibend.getText().trim().equals("0")) { - isCurrentlyLoading = false; - } else { - isCurrentlyLoading = true; - } - return isCurrentlyLoading; + private boolean isCurrentlyLoading() { + return task != null && !task.isDone(); }// end isCurrentlyLoading() public void resetValues() { diff --git a/dozentenmodul/src/main/java/gui/lecture/CreateLectureLink_GUI.java b/dozentenmodul/src/main/java/gui/lecture/CreateLectureLink_GUI.java index c4627a3a..7cfc1181 100644 --- a/dozentenmodul/src/main/java/gui/lecture/CreateLectureLink_GUI.java +++ b/dozentenmodul/src/main/java/gui/lecture/CreateLectureLink_GUI.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.UUID; import javax.swing.JButton; import javax.swing.JComboBox; @@ -79,7 +80,7 @@ public class CreateLectureLink_GUI extends JInternalFrame { private JTable tablemyImages = new JTable(); private JTextField textFieldName; private JLabel lblTotalResults; - private String uuid = null; + private String lectureUuid = null; private String[] titles = { "Image-Name", "Lizenzpflichtig", "OS", "Veranstaltung", "Verantwortlicher", "Letztes Update", "ID", "Version", "Template", "Beschreibung" }; @@ -385,13 +386,13 @@ public class CreateLectureLink_GUI extends JInternalFrame { formatter.format(Lecture.lecture.getEnddate()).toString(), Lecture.lecture.isActive(), imageID, SessionData.authToken, person.verantwortlicher.getTel(), - person.verantwortlicher.getFakultaet(), uuid, + person.verantwortlicher.getFakultaet(), lectureUuid, person.verantwortlicher.getHochschule()); System.out.println("imageID" + " " + imageID); - System.out.println("lectureID" + " " + uuid); + System.out.println("lectureID" + " " + lectureUuid); //set rights for this user - ThriftManager.getSatClient().writeLectureRights(uuid, + ThriftManager.getSatClient().writeLectureRights(lectureUuid, person.verantwortlicher.getRole(), SessionData.authToken, person.verantwortlicher.getHochschule(), person.verantwortlicher.getUserID()); @@ -401,7 +402,7 @@ public class CreateLectureLink_GUI extends JInternalFrame { .size(); i++) { //System.out.println("Writing additional rights for user "+RightsManagement.rightsManagement.getPermittedUserList().get(i).getUserID()+", User "+(i+1)+"/"+RightsManagement.rightsManagement.getPermittedUserList().size()); ThriftManager.getSatClient().writeAdditionalLectureRights( - uuid, + lectureUuid, RightsManagement.rightsManagement.getPermittedUserList().get(i) .getUserID(), RightsManagement.rightsManagement.getPermittedUserList().get(i) @@ -581,12 +582,7 @@ public class CreateLectureLink_GUI extends JInternalFrame { textAreadesc.setFont(new Font("Tahoma", Font.PLAIN, 11)); scrollPane.setViewportView(textAreadesc); - try { - uuid = ThriftManager.getSatClient().createRandomUUID(SessionData.authToken); - } catch (TException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } + lectureUuid = UUID.randomUUID().toString(); } diff --git a/dozentenmodul/src/main/java/gui/lecture/DeleteLecture_GUI.java b/dozentenmodul/src/main/java/gui/lecture/DeleteLecture_GUI.java index 71054020..e3523d3c 100644 --- a/dozentenmodul/src/main/java/gui/lecture/DeleteLecture_GUI.java +++ b/dozentenmodul/src/main/java/gui/lecture/DeleteLecture_GUI.java @@ -180,8 +180,7 @@ public class DeleteLecture_GUI extends JInternalFrame { JTextPane txtpnBitteWhlenSie = new JTextPane(); txtpnBitteWhlenSie.setEditable(false); txtpnBitteWhlenSie.setBackground(SystemColor.menu); - txtpnBitteWhlenSie - .setText("Wählen Sie bitte aus der unten stehenden Liste die zu löschende Veranstaltung aus."); + txtpnBitteWhlenSie.setText("Wählen Sie bitte aus der unten stehenden Liste die zu löschende Veranstaltung aus."); txtpnBitteWhlenSie.setBounds(10, 36, 509, 32); panel.add(txtpnBitteWhlenSie); } @@ -338,8 +337,7 @@ public class DeleteLecture_GUI extends JInternalFrame { // LOGGER.info("Lösche Veranstaltung: " + lectureID); try { - if (ThriftManager.getSatClient().deleteLecture(lectureID, SessionData.authToken, - person.verantwortlicher.getHochschule())) { + if (ThriftManager.getSatClient().deleteLecture(lectureID, SessionData.authToken)) { // delete successful LOGGER.info("Veranstaltung erfolgreich '" + lectureID + "' gelöscht."); diff --git a/dozentenmodul/src/main/java/models/Image.java b/dozentenmodul/src/main/java/models/Image.java index 1441a3ba..4bb1338d 100644 --- a/dozentenmodul/src/main/java/models/Image.java +++ b/dozentenmodul/src/main/java/models/Image.java @@ -4,7 +4,6 @@ public class Image { public static String ImageId; public static String Version; public static String Imagename; - public static String NewName; public static String Imagepath; public static String OS; public static int ShareMode; @@ -24,7 +23,6 @@ public class Image { ImageId = null; Version = null; Imagename = null; - NewName = null; Imagepath = null; OS = null; ShareMode = 0; diff --git a/dozentenmodul/src/main/java/util/GuiManager.java b/dozentenmodul/src/main/java/util/GuiManager.java index 9fa2814f..67671fcb 100644 --- a/dozentenmodul/src/main/java/util/GuiManager.java +++ b/dozentenmodul/src/main/java/util/GuiManager.java @@ -10,7 +10,6 @@ import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.HeadlessException; import java.awt.Rectangle; -import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; @@ -80,8 +79,7 @@ public abstract class GuiManager { // size management mainWindow.setBounds(0, 0, 785, 430); - mainWindow.setLocation( - (int) (rect.getWidth() / 2 - mainWindow.getWidth() / 2), + mainWindow.setLocation((int) (rect.getWidth() / 2 - mainWindow.getWidth() / 2), (int) (rect.getHeight() / 2 - mainWindow.getHeight() / 2)); try { @@ -99,7 +97,7 @@ public abstract class GuiManager { * Public function to show the given frame, replacing the current frame * * @param newFrame - * the new frame to show + * the new frame to show */ public static void show(JInternalFrame newFrame) { // first remove the current component @@ -131,8 +129,7 @@ public abstract class GuiManager { } // TODO else case - mainWindow.setTitle(newFrame.getTitle() != null ? newFrame.getTitle() - : "bwLehrpool Suite"); + mainWindow.setTitle(newFrame.getTitle() != null ? newFrame.getTitle() : "bwLehrpool Suite"); mainWindow.getContentPane().add(currentFrame, BorderLayout.CENTER); mainWindow.setBounds((int) mainWindow.getLocationOnScreen().getX(), (int) mainWindow.getLocationOnScreen().getY(), currentFrame.getWidth(), @@ -145,17 +142,16 @@ public abstract class GuiManager { * Public function to show the given frame, replacing the current frame * * @param newFrame - * the new frame to show + * the new frame to show * @param center - * true if the main window is to be centered, false otherwise + * true if the main window is to be centered, false otherwise */ public static void show(JInternalFrame newFrame, boolean center) { show(newFrame); if (center) { double xCenter = (rect.getWidth() / 2 - newFrame.getWidth() / 2); double yCenter = (rect.getHeight() / 2 - newFrame.getHeight() / 2); - mainWindow.setBounds((int) xCenter, (int) yCenter, newFrame.getWidth(), - newFrame.getHeight()); + mainWindow.setBounds((int) xCenter, (int) yCenter, newFrame.getWidth(), newFrame.getHeight()); } } @@ -164,18 +160,15 @@ public abstract class GuiManager { * main window * * @param popup - * The component to open as popup. Note this must be a JFrame. + * The component to open as popup. Note this must be a JFrame. */ public static void openPopup(Component popup) { if (!(popup instanceof JFrame)) { - LOGGER.error("Popup classes need to be JFrame, given a: " - + popup.getClass().getName()); + LOGGER.error("Popup classes need to be JFrame, given a: " + popup.getClass().getName()); return; } - int xPopup = (int) (mainWindow.getX() + (mainWindow.getWidth() / 2) - (popup - .getWidth() / 2)); - int yPopup = (int) (mainWindow.getY() + (mainWindow.getHeight() / 2) - (popup - .getHeight() / 2)); + int xPopup = (int) (mainWindow.getX() + (mainWindow.getWidth() / 2) - (popup.getWidth() / 2)); + int yPopup = (int) (mainWindow.getY() + (mainWindow.getHeight() / 2) - (popup.getHeight() / 2)); ((JFrame) popup).setLocation(xPopup, yPopup); ((JFrame) popup).setVisible(true); } @@ -213,7 +206,8 @@ public abstract class GuiManager { } /** - * Private function to determine whether the currentFrame has a 'HELP_MESSAGE' + * Private function to determine whether the currentFrame has a + * 'HELP_MESSAGE' * defined and to add it to the menu bar if found one. * * @return true if setting the help button to the menu bar worked, false @@ -225,16 +219,14 @@ public abstract class GuiManager { // "Hilfe" final String helpMessage; try { - helpMessage = (String) (currentFrame.getClass().getDeclaredField( - "HELP_MESSAGE").get(currentFrame)); + helpMessage = (String) (currentFrame.getClass().getDeclaredField("HELP_MESSAGE").get(currentFrame)); } catch (NoSuchFieldException e) { // only this case if interesting for us, // since we now we don't have a help message to show return false; - } catch (IllegalArgumentException | IllegalAccessException - | SecurityException e) { - LOGGER.error("Failed to check for 'HELP_MESSAGE' variable in '" - + currentFrame.getClass() + "' class, see trace: " + e); + } catch (IllegalArgumentException | IllegalAccessException | SecurityException e) { + LOGGER.error("Failed to check for 'HELP_MESSAGE' variable in '" + currentFrame.getClass() + + "' class, see trace: " + e); return false; } // print it for debugging purposes @@ -243,9 +235,8 @@ public abstract class GuiManager { mnNewMenu_Info.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent arg0) { - JOptionPane.showMessageDialog(currentFrame, - helpMessage != null ? helpMessage : "No help message.", - "Hilfe zu dieser Oberfläche", JOptionPane.INFORMATION_MESSAGE); + JOptionPane.showMessageDialog(currentFrame, helpMessage != null ? helpMessage + : "No help message.", "Hilfe zu dieser Oberfläche", JOptionPane.INFORMATION_MESSAGE); } }); mainWindow.getJMenuBar().add(mnNewMenu_Info); @@ -263,8 +254,7 @@ public abstract class GuiManager { gd = ge.getDefaultScreenDevice(); } catch (HeadlessException he) { he.printStackTrace(); - JOptionPane.showMessageDialog(null, - "Konnte kein Display ermittelt werden.", "Fehler", + JOptionPane.showMessageDialog(null, "Konnte kein Display ermittelt werden.", "Fehler", JOptionPane.ERROR_MESSAGE); return false; } @@ -273,12 +263,28 @@ public abstract class GuiManager { rect = gc.getBounds(); if (rect == null) { - JOptionPane.showMessageDialog(null, - "Konnte die Resolution des Bildschirms nicht ermitteln!", "Fehler", - JOptionPane.ERROR_MESSAGE); + JOptionPane.showMessageDialog(null, "Konnte die Resolution des Bildschirms nicht ermitteln!", + "Fehler", JOptionPane.ERROR_MESSAGE); return false; } else { return true; } } + + /** + * Generic helper to show a message box to the user, and optionally log the message to the log file. + * + * @param message Message to display. Can be multi line. + * @param messageType Type of message (warning, information) + * @param logger Logger instance to log to. Can be null. + * @param exception Exception related to this message. Can be null. + */ + public static void showMessageBox(String message, MessageType messageType, Logger logger, + Throwable exception) { + if (logger != null) + logger.log(messageType.logPriority, message, exception); + if (exception != null) + message += "\n\n" + exception.getClass().getSimpleName(); + JOptionPane.showMessageDialog(mainWindow, message, messageType.title, messageType.optionPaneId); + } } diff --git a/dozentenmodul/src/main/java/util/MessageType.java b/dozentenmodul/src/main/java/util/MessageType.java new file mode 100644 index 00000000..294e28d6 --- /dev/null +++ b/dozentenmodul/src/main/java/util/MessageType.java @@ -0,0 +1,23 @@ +package util; + +import javax.swing.JOptionPane; + +import org.apache.log4j.Priority; + +@SuppressWarnings("deprecation") +public enum MessageType { + DEBUG(JOptionPane.INFORMATION_MESSAGE, "Debug", Priority.DEBUG), + INFO(JOptionPane.INFORMATION_MESSAGE, "Hinweis", Priority.INFO), + WARNING(JOptionPane.WARNING_MESSAGE, "Warnung", Priority.WARN), + ERROR(JOptionPane.ERROR_MESSAGE, "Fehler", Priority.ERROR); + + public final String title; + public final int optionPaneId; + public final Priority logPriority; + + private MessageType(int paneId, String title, Priority prio) { + this.title = title; + this.optionPaneId = paneId; + this.logPriority = prio; + } +} |