summaryrefslogtreecommitdiffstats
path: root/dozentenmodulserver/src
diff options
context:
space:
mode:
authorSimon Rettberg2015-06-02 19:53:31 +0200
committerSimon Rettberg2015-06-02 19:53:31 +0200
commit1bc83891c68ee269727e81a13cc70da698bcc7a7 (patch)
treeb052a72ad7d65864068752f71c5ed2b49a171276 /dozentenmodulserver/src
parent[server] Started work on the internal file server (diff)
downloadtutor-module-1bc83891c68ee269727e81a13cc70da698bcc7a7.tar.gz
tutor-module-1bc83891c68ee269727e81a13cc70da698bcc7a7.tar.xz
tutor-module-1bc83891c68ee269727e81a13cc70da698bcc7a7.zip
[server] Compiling again, still lots of stubs
Diffstat (limited to 'dozentenmodulserver/src')
-rw-r--r--dozentenmodulserver/src/main/java/fileserv/ActiveUpload.java54
-rw-r--r--dozentenmodulserver/src/main/java/fileserv/ChunkList.java78
-rw-r--r--dozentenmodulserver/src/main/java/fileserv/FileChunk.java28
-rw-r--r--dozentenmodulserver/src/main/java/fileserv/FileServer.java64
-rw-r--r--dozentenmodulserver/src/main/java/models/Configuration.java87
-rw-r--r--dozentenmodulserver/src/main/java/server/ServerHandler.java621
-rw-r--r--dozentenmodulserver/src/main/java/server/SessionManager.java84
-rw-r--r--dozentenmodulserver/src/main/java/server/StartServer.java45
-rw-r--r--dozentenmodulserver/src/main/java/sql/SQL.java265
-rw-r--r--dozentenmodulserver/src/main/java/thrift/MasterThriftConnection.java43
-rw-r--r--dozentenmodulserver/src/main/java/thrift/SessionData.java33
-rw-r--r--dozentenmodulserver/src/main/java/thrift/ThriftConnection.java54
-rw-r--r--dozentenmodulserver/src/main/java/util/Constants.java21
-rw-r--r--dozentenmodulserver/src/main/java/util/FileSystem.java25
-rw-r--r--dozentenmodulserver/src/main/java/util/Formatter.java59
-rw-r--r--dozentenmodulserver/src/main/java/util/Util.java45
16 files changed, 867 insertions, 739 deletions
diff --git a/dozentenmodulserver/src/main/java/fileserv/ActiveUpload.java b/dozentenmodulserver/src/main/java/fileserv/ActiveUpload.java
index cf73a413..256f8b8d 100644
--- a/dozentenmodulserver/src/main/java/fileserv/ActiveUpload.java
+++ b/dozentenmodulserver/src/main/java/fileserv/ActiveUpload.java
@@ -1,10 +1,11 @@
package fileserv;
+import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
+import java.nio.ByteBuffer;
import java.util.List;
-import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ThreadPoolExecutor;
import org.apache.log4j.Logger;
@@ -12,6 +13,7 @@ import org.openslx.filetransfer.DataReceivedCallback;
import org.openslx.filetransfer.Downloader;
import org.openslx.filetransfer.FileRange;
import org.openslx.filetransfer.WantRangeCallback;
+import org.openslx.imagemaster.thrift.iface.UserInfo;
public class ActiveUpload {
private static final Logger LOGGER = Logger.getLogger(ActiveUpload.class);
@@ -21,19 +23,28 @@ public class ActiveUpload {
*/
private Downloader download = null;
- private final String destinationFile;
+ private final File destinationFile;
private final RandomAccessFile outFile;
- private ConcurrentLinkedQueue<FileChunk> chunks = new ConcurrentLinkedQueue<>();
+ private final ChunkList chunks;
- // TODO: Hashlist for verification
+ private final long fileSize;
- public ActiveUpload(String destinationFile, long fileSize, List<byte[]> sha1Sums)
+ /**
+ * User owning this uploaded file.
+ */
+ private final UserInfo owner;
+
+ // TODO: Use HashList for verification
+
+ public ActiveUpload(UserInfo owner, File destinationFile, long fileSize, List<ByteBuffer> sha1Sums)
throws FileNotFoundException {
this.destinationFile = destinationFile;
- outFile = new RandomAccessFile(destinationFile, "rw");
- FileChunk.createChunkList(chunks, fileSize, sha1Sums);
+ this.outFile = new RandomAccessFile(destinationFile, "rw");
+ this.chunks = new ChunkList(fileSize, sha1Sums);
+ this.owner = owner;
+ this.fileSize = fileSize;
}
/**
@@ -45,7 +56,7 @@ public class ActiveUpload {
* discarded
*/
public synchronized boolean addConnection(Downloader connection, ThreadPoolExecutor pool) {
- if (download != null)
+ if (download != null || chunks.isComplete())
return false;
download = connection;
pool.execute(new Runnable() {
@@ -55,7 +66,7 @@ public class ActiveUpload {
if (!download.download(cbh, cbh) && cbh.currentChunk != null) {
// If the download failed and we have a current chunk, put it back into
// the queue, so it will be handled again later...
- chunks.add(cbh.currentChunk);
+ chunks.markFailed(cbh.currentChunk);
}
}
});
@@ -86,6 +97,27 @@ public class ActiveUpload {
}
/**
+ * Get user owning this upload. Can be null in special cases.
+ *
+ * @return instance of UserInfo for the according user.
+ */
+ public UserInfo getOwner() {
+ return this.owner;
+ }
+
+ public boolean isComplete() {
+ return chunks.isComplete() && destinationFile.length() == this.fileSize;
+ }
+
+ public File getDestinationFile() {
+ return this.destinationFile;
+ }
+
+ public long getSize() {
+ return this.fileSize;
+ }
+
+ /**
* Callback class for an instance of the Downloader, which supplies
* the Downloader with wanted file ranges, and handles incoming data.
*/
@@ -111,11 +143,13 @@ public class ActiveUpload {
// This needs to be async (own thread) so will be a little complicated
}
// Get next missing chunk
- currentChunk = chunks.poll();
+ currentChunk = chunks.getMissing();
if (currentChunk == null)
return null; // No more chunks, returning null tells the Downloader we're done.
return currentChunk.range;
}
}
+ // TODO: Clean up old stale uploads
+
}
diff --git a/dozentenmodulserver/src/main/java/fileserv/ChunkList.java b/dozentenmodulserver/src/main/java/fileserv/ChunkList.java
new file mode 100644
index 00000000..95b3e1fa
--- /dev/null
+++ b/dozentenmodulserver/src/main/java/fileserv/ChunkList.java
@@ -0,0 +1,78 @@
+package fileserv;
+
+import java.nio.ByteBuffer;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+
+public class ChunkList {
+
+ private static final Logger LOGGER = Logger.getLogger(ChunkList.class);
+
+ /**
+ * Chunks that are missing from the file
+ */
+ private final List<FileChunk> missingChunks = new LinkedList<>();
+
+ /**
+ * Chunks that are currently being uploaded or hash-checked
+ */
+ private final List<FileChunk> pendingChunks = new LinkedList<>();
+
+ // Do we need to keep valid chunks, or chunks that failed too many times?
+
+ public ChunkList(long fileSize, List<ByteBuffer> sha1Sums) {
+ FileChunk.createChunkList(missingChunks, fileSize, sha1Sums);
+ }
+
+ /**
+ * Get a missing chunk, marking it pending.
+ *
+ * @return chunk marked as missing
+ */
+ public synchronized FileChunk getMissing() {
+ if (missingChunks.isEmpty())
+ return null;
+ FileChunk c = missingChunks.remove(0);
+ pendingChunks.add(c);
+ return c;
+ }
+
+ /**
+ * Mark a chunk currently transferring as successfully transfered.
+ *
+ * @param c The chunk in question
+ */
+ public synchronized void markSuccessful(FileChunk c) {
+ if (!pendingChunks.remove(c)) {
+ LOGGER.warn("Inconsistent state: markTransferred called for Chunk " + c.toString()
+ + ", but chunk is not marked as currently transferring!");
+ return;
+ }
+ }
+
+ /**
+ * Mark a chunk currently transferring or being hash checked as failed
+ * transfer. This increases its fail count and re-adds it to the list of
+ * missing chunks.
+ *
+ * @param c The chunk in question
+ * @return Number of times transfer of this chunk failed
+ */
+ public synchronized int markFailed(FileChunk c) {
+ if (!pendingChunks.remove(c)) {
+ LOGGER.warn("Inconsistent state: markTransferred called for Chunk " + c.toString()
+ + ", but chunk is not marked as currently transferring!");
+ return -1;
+ }
+ // Add as first element so it will be re-transmitted immediately
+ missingChunks.add(0, c);
+ return c.incFailed();
+ }
+
+ public synchronized boolean isComplete() {
+ return missingChunks.isEmpty() && pendingChunks.isEmpty();
+ }
+
+}
diff --git a/dozentenmodulserver/src/main/java/fileserv/FileChunk.java b/dozentenmodulserver/src/main/java/fileserv/FileChunk.java
index 2fee6378..1a95d27c 100644
--- a/dozentenmodulserver/src/main/java/fileserv/FileChunk.java
+++ b/dozentenmodulserver/src/main/java/fileserv/FileChunk.java
@@ -1,39 +1,55 @@
package fileserv;
+import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.List;
import org.openslx.filetransfer.FileRange;
public class FileChunk {
- public static final int CHUNK_SIZE = 16 * 1024 * 1024;
+
+ public static final int CHUNK_SIZE_MIB = 16;
+ public static final int CHUNK_SIZE = CHUNK_SIZE_MIB * (1024 * 1024);
public final FileRange range;
public final byte[] sha1sum;
+ private int failCount = 0;
public FileChunk(long startOffset, long endOffset, byte[] sha1sum) {
this.range = new FileRange(startOffset, endOffset);
this.sha1sum = sha1sum;
}
+ /**
+ * Signal that transferring this chunk seems to have failed (checksum
+ * mismatch).
+ *
+ * @return Number of times the transfer failed now
+ */
+ public synchronized int incFailed() {
+ return ++failCount;
+ }
+
+ //
+
public static int fileSizeToChunkCount(long fileSize) {
return (int) ((fileSize + CHUNK_SIZE - 1) / CHUNK_SIZE);
}
- public static void createChunkList(Collection<FileChunk> list, long fileSize, List<byte[]> sha1sums) {
+ public static void createChunkList(Collection<FileChunk> list, long fileSize, List<ByteBuffer> sha1Sums) {
if (fileSize < 0)
throw new IllegalArgumentException("fileSize cannot be negative");
long chunkCount = fileSizeToChunkCount(fileSize);
- if (sha1sums != null) {
- if (sha1sums.size() != chunkCount)
+ if (sha1Sums != null) {
+ if (sha1Sums.size() != chunkCount)
throw new IllegalArgumentException(
"Passed a sha1sum list, but hash count in list doesn't match expected chunk count");
long offset = 0;
- for (byte[] sha1sum : sha1sums) { // Do this as we don't know how efficient List.get(index) is...
+ for (ByteBuffer sha1sum : sha1Sums) { // Do this as we don't know how efficient List.get(index) is...
long end = offset + CHUNK_SIZE;
if (end > fileSize)
end = fileSize;
- list.add(new FileChunk(offset, end, sha1sum));
+ list.add(new FileChunk(offset, end, sha1sum.array()));
offset = end;
}
return;
diff --git a/dozentenmodulserver/src/main/java/fileserv/FileServer.java b/dozentenmodulserver/src/main/java/fileserv/FileServer.java
index 446b982e..8322e2e9 100644
--- a/dozentenmodulserver/src/main/java/fileserv/FileServer.java
+++ b/dozentenmodulserver/src/main/java/fileserv/FileServer.java
@@ -1,13 +1,24 @@
package fileserv;
+import java.io.File;
+import java.io.FileNotFoundException;
import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.Iterator;
+import java.util.List;
import java.util.Map;
+import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.openslx.filetransfer.Downloader;
import org.openslx.filetransfer.IncomingEvent;
import org.openslx.filetransfer.Listener;
import org.openslx.filetransfer.Uploader;
+import org.openslx.imagemaster.thrift.iface.UserInfo;
+import org.openslx.sat.thrift.iface.TUploadRejectedException;
+
+import util.Constants;
+import util.Formatter;
public class FileServer implements IncomingEvent {
@@ -21,6 +32,15 @@ public class FileServer implements IncomingEvent {
*/
private Map<String, ActiveUpload> uploads = new ConcurrentHashMap<>();
+ private static final FileServer globalInstance = new FileServer();
+
+ private FileServer() {
+ }
+
+ public static FileServer instance() {
+ return globalInstance;
+ }
+
public boolean start() {
boolean ret = plainListener.start();
// TODO: Start SSL listener too
@@ -39,4 +59,48 @@ public class FileServer implements IncomingEvent {
}
+ /**
+ * Get an upload instance by given token.
+ *
+ * @param uploadToken
+ * @return
+ */
+ public ActiveUpload getUploadByToken(String uploadToken) {
+ return uploads.get(uploadToken);
+ }
+
+ public String createNewUserUpload(UserInfo owner, long fileSize, List<ByteBuffer> sha1Sums)
+ throws TUploadRejectedException, FileNotFoundException {
+ Iterator<ActiveUpload> it = uploads.values().iterator();
+ int activeUploads = 0;
+ while (it.hasNext()) {
+ ActiveUpload upload = it.next();
+ if (upload.isComplete()) {
+ // TODO: Check age (short timeout) and remove
+ continue;
+ } else {
+ // Check age (long timeout) and remove
+ }
+ activeUploads++;
+ }
+ if (activeUploads > Constants.MAX_UPLOADS)
+ throw new TUploadRejectedException("Server busy. Too many running uploads.");
+ File destinationFile = null;
+ do {
+ destinationFile = Formatter.getTempImageName();
+ } while (destinationFile.exists());
+ ActiveUpload upload = new ActiveUpload(owner, destinationFile, fileSize, sha1Sums);
+ String key = UUID.randomUUID().toString();
+ uploads.put(key, upload);
+ return key;
+ }
+
+ public int getPlainPort() {
+ return plainListener.getPort();
+ }
+
+ public int getSslPort() {
+ return 0; // TODO
+ }
+
}
diff --git a/dozentenmodulserver/src/main/java/models/Configuration.java b/dozentenmodulserver/src/main/java/models/Configuration.java
index 1e616466..244e542b 100644
--- a/dozentenmodulserver/src/main/java/models/Configuration.java
+++ b/dozentenmodulserver/src/main/java/models/Configuration.java
@@ -1,39 +1,72 @@
package models;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+import org.apache.log4j.Logger;
+import org.joda.time.format.DateTimeFormat;
+import org.joda.time.format.DateTimeFormatter;
+
public class Configuration {
-
- private String absolute_path;
- private String sql_connection;
- private String sql_user;
- private String sql_pass;
-
- public static Configuration config =new Configuration();
-
- public String getAbsolute_path() {
- return absolute_path;
- }
- public void setAbsolute_path(String absolute_path) {
- this.absolute_path = absolute_path;
+
+ private static final Logger LOGGER = Logger.getLogger(Configuration.class);
+ private static final DateTimeFormatter subdirDate = DateTimeFormat.forPattern("yy-MM");
+
+ private static File vmStoreBasePath;
+ private static File vmStoreProdPath;
+ private static String dbUri;
+ private static String dbUsername;
+ private static String dbPassword;
+
+ public static boolean load() throws IOException {
+ // Load configuration from java properties file
+ Properties prop = new Properties();
+ InputStream in = new FileInputStream("./config.properties");
+ try {
+ prop.load(in);
+ } finally {
+ in.close();
+ }
+
+ vmStoreBasePath = new File(prop.getProperty("vmstore.path"));
+ vmStoreProdPath = new File(vmStoreBasePath, "prod");
+ dbUri = prop.getProperty("db.uri");
+ dbUsername = prop.getProperty("db.username");
+ dbPassword = prop.getProperty("db.password");
+
+ // Currently all fields are mandatory but there might be optional settings in the future
+ return vmStoreBasePath != null && dbUri != null && dbUsername != null && dbPassword != null;
}
- public String getSql_connection() {
- return sql_connection;
+
+ // Static ("real") fields
+
+ public static File getVmStoreBasePath() {
+ return vmStoreBasePath;
}
- public void setSql_connection(String sql_connection) {
- this.sql_connection = sql_connection;
+
+ public static String getDbUri() {
+ return dbUri;
}
- public String getSql_user() {
- return sql_user;
+
+ public static String getDbUsername() {
+ return dbUsername;
}
- public void setSql_user(String sql_user) {
- this.sql_user = sql_user;
+
+ public static String getDbPassword() {
+ return dbPassword;
}
- public String getSql_pass() {
- return sql_pass;
+
+ public static File getVmStoreProdPath() {
+ return vmStoreProdPath;
}
- public void setSql_pass(String sql_pass) {
- this.sql_pass = sql_pass;
+
+ // Dynamically Computed fields
+
+ public static File getCurrentVmStorePath() {
+ return new File(vmStoreProdPath, subdirDate.print(System.currentTimeMillis()));
}
-
-
}
diff --git a/dozentenmodulserver/src/main/java/server/ServerHandler.java b/dozentenmodulserver/src/main/java/server/ServerHandler.java
index b5d7bc54..bc16273f 100644
--- a/dozentenmodulserver/src/main/java/server/ServerHandler.java
+++ b/dozentenmodulserver/src/main/java/server/ServerHandler.java
@@ -1,13 +1,9 @@
package server;
import java.io.File;
+import java.io.FileNotFoundException;
import java.io.IOException;
-import java.math.BigInteger;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
+import java.nio.ByteBuffer;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@@ -19,244 +15,113 @@ import models.Configuration;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
-import org.openslx.imagemaster.thrift.iface.ImageServer.Client;
import org.openslx.imagemaster.thrift.iface.UserInfo;
import org.openslx.sat.thrift.iface.Image;
import org.openslx.sat.thrift.iface.Lecture;
import org.openslx.sat.thrift.iface.Person;
import org.openslx.sat.thrift.iface.Server;
-import org.openslx.sat.thrift.iface.User;
+import org.openslx.sat.thrift.iface.TUploadFinishException;
+import org.openslx.sat.thrift.iface.TUploadRejectedException;
+import org.openslx.sat.thrift.iface.TransferInformation;
import org.openslx.sat.thrift.version.Version;
import sql.SQL;
-import thrift.MasterThriftConnection;
+import util.Constants;
+import util.FileSystem;
+import util.Formatter;
+import fileserv.ActiveUpload;
+import fileserv.FileServer;
public class ServerHandler implements Server.Iface {
- private static Logger log = Logger.getLogger(ServerHandler.class);
- static SQL sql = new SQL();
-
- // saves the current tokens and the mapped userdata, returning from the server
- // TODO: Handle/cache tokens in own class, add timeout to tokens in case client never marks it invalid
- private Map<String, UserInfo> tokenManager = new HashMap<>();
-
- public boolean authenticated(String token) throws TException {
- if (tokenManager.get(token) != null) {
- // user found in tokenManager, session was set to valid once before
- // (cached session, no further action needed)
- return true;
- } else {
- MasterThriftConnection thrift = new MasterThriftConnection();
- Client client = thrift.getMasterThriftConnection();
-
- // user not in tokenManager, check authentication, then add user to tokenManager
- log.info("token is: " + token);
- UserInfo ui = null;
- if ((ui = client.getUserFromToken(token)) != null) {
- // user was authenticated by the masterserver, cache the data
- tokenManager.put(token, ui);
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * local function, which gets userdata from the tokenmanager, not the
- * masterserver implemented, as there is no need for userdata in each
- * function, so return type of authenticated should stay boolean
- */
- private UserInfo getUserFromToken(String token) {
- UserInfo ui = tokenManager.get(token);
- return ui;
- }
-
- public boolean setSessionInvalid(String token) {
- log.info("token disabling.. round one");
- log.info(tokenManager.get(token));
-
- tokenManager.remove(token);
-
- log.info("token disabling.. round two");
- log.info(tokenManager.get(token));
-
- // check if deletion worked and token isn't stored anymore
- return tokenManager.get(token) == null;
- }
-
- @Override
- public User getFtpUser(String token) throws TException {
- if (authenticated(token)) {
-
- log.info("returning FTPUser...");
- User user = new User();
- user.setUserName(UUID.randomUUID().toString().substring(0, 8));
- user.setPassword(getEncodedSha1Sum(UUID.randomUUID().toString().substring(0, 8)));
- if (Configuration.config.getAbsolute_path().endsWith("/")) {
- user.setPath(Configuration.config.getAbsolute_path());
- } else {
- user.setPath(Configuration.config.getAbsolute_path() + "/");
- }
-
- // check if folder temp and folder prod exist
- if (folderTempExists() == true && folderProdExists() == true) {
- sql.writeFTPUser(user.getUserName(), user.getPassword());
- return user;
- } else {
- log.info("Error: returning null user");
- return null;
- }
- }
- return null;
-
- }
-
- public boolean folderTempExists() {
- // check if folder temp exists, otherwise create it
- Path path = null;
- if (Configuration.config.getAbsolute_path().endsWith("/")) {
- path = Paths.get(Configuration.config.getAbsolute_path() + "temp");
- } else {
- path = Paths.get(Configuration.config.getAbsolute_path() + "/temp");
- }
-
- if (Files.exists(path) == true) {
- log.info("folder '" + path + "' exists, no further action");
- return true;
- } else {
- // create directory and set permissions
- boolean success = (new File(path + "")).mkdirs();
-
- if (!success) {
- log.info("failed to create folder '" + path + "'");
- return false;
- } else {
- // set permissions
- try {
- Runtime.getRuntime().exec("chmod 777 " + path);
- } catch (IOException e) {
- e.printStackTrace();
- }
- log.info("folder '" + path + "' successfully created");
- return true;
- }
- }
-
- }// end folderTempExists()
-
- public boolean folderProdExists() {
- // check if folder temp exists, otherwise create it
- Path path = null;
- if (Configuration.config.getAbsolute_path().endsWith("/")) {
- path = Paths.get(Configuration.config.getAbsolute_path() + "prod");
- } else {
- path = Paths.get(Configuration.config.getAbsolute_path() + "/prod");
- }
-
- if (Files.exists(path) == true) {
- log.info("folder '" + path + "' exists, no further action");
- return true;
- } else {
- // create directory and set permissions
- boolean success = (new File(path + "")).mkdirs();
-
- if (!success) {
- log.info("failed to create folder '" + path + "'");
- return false;
- } else {
- // set permissions
- // TODO: Just no. Check if it's writable and bail out if not, but don't
- // blindly try to set permissions when you don't even check if it worked.
- try {
- Runtime.getRuntime().exec("chmod 777 " + path);
- } catch (IOException e) {
- e.printStackTrace();
- }
- log.info("folder '" + path + "' successfully created");
- return true;
- }
- }
-
- }// end folderProdExists()
-
- public String getEncodedSha1Sum(String key) {
+ private static final Logger log = Logger.getLogger(ServerHandler.class);
+ private static final SQL sql = new SQL();
+ private static final FileServer fileServer = FileServer.instance();
+
+ @Override
+ public String finishImageUpload(String imageName, String description, boolean license, boolean internet,
+ long shareMode, String os, String uploadToken) throws TException {
+ ActiveUpload upload = fileServer.getUploadByToken(uploadToken);
+ if (upload == null) {
+ log.warn("A client called finishImageUpload, but the given token is unknown");
+ throw new TUploadFinishException("Your upload token is invalid");
+ }
+ if (!upload.isComplete()) {
+ log.warn("A client called finishImageUpload for an upload that is still running");
+ throw new TUploadFinishException("Cannot finish upload: Still in progress...");
+ }
+ // We need an owner for the upload to handle it properly
+ UserInfo user = upload.getOwner();
+ if (user == null) {
+ log.warn("A client called finishImageUpload, the uploadToken was valid, but the upload doesn't have an owner");
+ throw new TUploadFinishException("Your upload doesn't have an owner. (This should not happen!)");
+ }
+ // We also need a temp file
+ File file = upload.getDestinationFile();
+ if (file == null || !file.getName().endsWith(Constants.INCOMPLETE_UPLOAD_SUFFIX)) {
+ log.warn("A client called finishImageUpload, but there is no temp file involved or it has the wrong extension ("
+ + file + ")");
+ throw new TUploadFinishException("Your upload doesn't have a matching temp file on the server.");
+ }
+
+ // Ready to go. First step: Rename temp file to something usable
+ File destination = new File(file.getParent(), Formatter.vmName(user, imageName));
+ // Sanity check: destination should be a sub directory of the vmStorePath
+ String relPath = FileSystem.getRelativePath(destination, Configuration.getVmStoreBasePath());
+ if (relPath == null) {
+ log.warn(destination.getAbsolutePath() + " is not a subdir of "
+ + Configuration.getVmStoreBasePath().getAbsolutePath());
+ throw new TUploadFinishException(
+ "Your file lies outside of the vm store directory (This is a server side issue).");
+ }
+ // Execute rename
+ boolean ret = false;
+ Exception renameException = null;
try {
- MessageDigest md = MessageDigest.getInstance("SHA1");
- md.update(key.getBytes());
- log.info("successfully returned EncodedSha1Sum"); // How do you know? You didn't return anything yet
- return new BigInteger(1, md.digest()).toString(16);
- } catch (NoSuchAlgorithmException e) {
- // handle error case to taste
+ ret = file.renameTo(destination);
+ } catch (Exception e) {
+ ret = false;
+ renameException = e;
}
- return null;
- }
-
- @Override
- public long DeleteFtpUser(String user, String token) throws TException {
- if (authenticated(token)) {
- return sql.DeleteUser(user);
+ if (!ret) {
+ // Rename failed :-(
+ log.warn("Could not rename '" + file.getAbsolutePath() + "' to '" + destination.getAbsolutePath()
+ + "'", renameException);
}
- return -1;
- }
- @Override
- public String getPathOfImage(String image_id, String version, String token) throws TException {
- if (authenticated(token)) {
- log.info("successfully returned PathOfImage: " + sql.getPathOfImage(image_id, version));
-
- return sql.getPathOfImage(image_id, version);
- }
- return null;
- }
+ // Now insert meta data into DB
- @Override
- public String setInstitution(String university, String token) throws TException {
- if (authenticated(token)) {
- // TODO: wat. Institutions are defined globally on the master server, including their ID
- return sql.setInstitution(university);
+ final String imageUuid = UUID.randomUUID().toString();
+ final String mode;
+ if (shareMode == 0) {
+ mode = "only_local";
+ } else {
+ mode = "to_be_published";
}
- return null;
- }
-
- @Override
- public boolean writeVLdata(String imagename, String desc, String Tel, String Fak, boolean license,
- boolean internet, long ram, long cpu, String imagePath, boolean isTemplate, long filesize,
- long shareMode, String os, String uid, String token, String userID) throws TException {
-
- if (authenticated(token)) {
- String mode = null;
-
- if (shareMode == 0) {
- mode = "only_local";
- } else {
- mode = "to_be_published";
- }
- // OS impl Select and write
- // ACHTUNG: Anzahl der Leerzeichen muss eingehalten werden:
- // 'Windows 7 32 bit"
- // TODO: Might be the biggest mess around here. We should define OS types on the
- // master server in the future and have them synced to the satellite.
- String pk_os = sql.getOSpk(os.substring(0, nthIndexOf(os, " ", 2)),
- os.substring(nthIndexOf(os, " ", 2), os.lastIndexOf(" ")).replace(" ", ""));
+ // OS impl Select and write
+ // ACHTUNG: Anzahl der Leerzeichen muss eingehalten werden:
+ // 'Windows 7 32 bit"
+ // TODO: Might be the biggest mess around here. We should define OS types on the
+ // master server in the future and have them synced to the satellite.
+ String pk_os = sql.getOSpk(os.substring(0, nthIndexOf(os, " ", 2)),
+ os.substring(nthIndexOf(os, " ", 2), os.lastIndexOf(" ")).replace(" ", ""));
- sql.setImageData(userID, license, internet, cpu, ram, imagename, desc, imagePath, filesize, mode,
- pk_os, uid);
+ ret = sql.writeNewImageData(user.userId, license, internet, imageName, description, relPath,
+ upload.getSize(), mode, pk_os, imageUuid);
+ if (!ret)
+ throw new TUploadFinishException(
+ "Image uploaded successfully, but could not be inserted into data base.");
- log.info("userID in serverhandler was: " + userID);
+ return imageUuid;
- log.info("written VLdata");
- return true;
- }
- return false;
}
@Override
// @param: userID - deprecated, to be removed while setting up new suite-architecture
public List<Image> getImageListPermissionWrite(String userID, String token) throws TException {
- if (authenticated(token)) {
- UserInfo ui = getUserFromToken(token);
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getImageListPermissionWrite(ui.getUserId());
}
return null;
@@ -265,8 +130,8 @@ public class ServerHandler implements Server.Iface {
@Override
// @param: userID - deprecated, to be removed while setting up new suite-architecture
public List<Image> getImageListPermissionRead(String userID, String token) throws TException {
- if (authenticated(token)) {
- UserInfo ui = getUserFromToken(token);
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getImageListPermissionRead(ui.getUserId());
}
return null;
@@ -275,8 +140,8 @@ public class ServerHandler implements Server.Iface {
@Override
// @param: userID - deprecated, to be removed while setting up new suite-architecture
public List<Image> getImageListPermissionLink(String userID, String token) throws TException {
- if (authenticated(token)) {
- UserInfo ui = getUserFromToken(token);
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getImageListPermissionLink(ui.getUserId());
}
return null;
@@ -285,8 +150,8 @@ public class ServerHandler implements Server.Iface {
@Override
// @param: userID - deprecated, to be removed while setting up new suite-architecture
public List<Image> getImageListPermissionAdmin(String userID, String token) throws TException {
- if (authenticated(token)) {
- UserInfo ui = getUserFromToken(token);
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getImageListPermissionAdmin(ui.getUserId());
}
return null;
@@ -294,7 +159,8 @@ public class ServerHandler implements Server.Iface {
@Override
public List<Image> getImageListAllTemplates(String token) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getImageListAllTemplates();
}
return null;
@@ -302,7 +168,8 @@ public class ServerHandler implements Server.Iface {
@Override
public List<String> getAllOS(String token) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getAllOS();
}
return null;
@@ -318,12 +185,11 @@ public class ServerHandler implements Server.Iface {
@Override
public Map<String, String> getPersonData(String Vorname, String Nachname, String token) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
Map<String, String> map = new HashMap<>();
- UserInfo ui = getUserFromToken(token);
-
map.put("mail", ui.getEMail());
map.put("Nachname", ui.getLastName());
map.put("Vorname", ui.getFirstName());
@@ -337,10 +203,11 @@ public class ServerHandler implements Server.Iface {
return null;
}
+ @Override
public void setPerson(String userID, String token, String institution) throws TException {
// TODO: Again, what's going on with institution as a parameter here? It's part of the UserInfo...
- if (authenticated(token)) {
- UserInfo ui = getUserFromToken(token);
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
sql.setPerson(userID, ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), institution);
}
}
@@ -349,9 +216,9 @@ public class ServerHandler implements Server.Iface {
public boolean writeLecturedata(String name, String shortdesc, String desc, String startDate,
String endDate, boolean isActive, String imageID, String token, String Tel, String Fak,
String lectureID, String university) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
// TODO: Check if the user has the permissions to set this lecture's meta data...
- UserInfo ui = getUserFromToken(token);
Map<String, String> map = new HashMap<String, String>();
int imageversion = 0;
@@ -372,76 +239,34 @@ public class ServerHandler implements Server.Iface {
}
@Override
- public boolean startFileCopy(String filename, String token) throws TException {
- if (authenticated(token)) {
- // copy file from folder temp to folder prod
- String file = Configuration.config.getAbsolute_path() + "temp/" + filename;
- File tmpFile = new File(file);
-
- log.info("Trying to move file to '/srv/openslx/nfs/prod/" + tmpFile.getName() + "'");
- try {
- FileUtils.moveFile(tmpFile, new File(Configuration.config.getAbsolute_path() + "prod/"
- + filename));
- // int ret = sql.UpdateImagePath(filename);
- if (sql.UpdateImagePath(filename) == 0) {
- log.info("file moved and database updated.");
- }
-
- } catch (IOException e) {
- log.info("Failed to move file.");
- e.printStackTrace();
- }
- }
- return true;
- }
-
- @Override
public Map<String, String> getImageData(String imageid, String imageversion, String token)
throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getImageData(imageid, imageversion);
}
return null;
}
@Override
- public boolean updateImageData(String name, String newName, String desc, String image_path,
- boolean license, boolean internet, long ram, long cpu, String id, String version,
- boolean isTemplate, long filesize, long shareMode, String os, String token) throws TException {
-
- if (authenticated(token)) {
-
- // get old_image_path
- String old_image_path = sql.getFile(id, version);
-
- String mode = null;
-
+ public boolean updateImageData(String userToken, String imageId, String newName, String desc,
+ boolean license, boolean internet, long shareMode, String os) throws TException {
+ UserInfo ui = SessionManager.get(userToken);
+ if (ui != null) {
+ final String mode;
if (shareMode == 0) {
mode = "only_local";
} else {
mode = "to_be_published";
}
+
String pk_os = sql.getOSpk(os.substring(0, nthIndexOf(os, " ", 2)),
os.substring(nthIndexOf(os, " ", 2), os.lastIndexOf(" ")).replace(" ", ""));
// do database update - if successful then delete old file from
// drive
- int val = sql.UpdateImageData(name, newName, desc, image_path, license, internet, cpu, ram, id,
- version, isTemplate, filesize, mode, pk_os);
-
- // check if new file has been uploaded by checking if the new file
- // path equals the old file path
- // if so, no new file was uploaded. Else delete old file
- if (val == 0 && (!old_image_path.substring(5).matches(image_path.substring(5)))) {
- // update was successful - delete old file
- // log.debug("deleting file "+old_image_path);
- deleteImageByPath(old_image_path);
- } else {
- // update was not successful - delete new file
- // TODO not yet implemented
- // log.debug("doing nothing because no new file was uploaded..");
+ return sql.updateImageData(newName, desc, license, internet, imageId, mode, pk_os);
- }
}
return false;
}
@@ -457,8 +282,8 @@ public class ServerHandler implements Server.Iface {
@Override
public List<Lecture> getLectureListPermissionRead(String token) throws TException {
- if (authenticated(token)) {
- UserInfo ui = getUserFromToken(token);
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
// log.info("returning LectureListRead");
return sql.getLectureListPermissionRead(ui.getUserId());
}
@@ -467,8 +292,8 @@ public class ServerHandler implements Server.Iface {
@Override
public List<Lecture> getLectureListPermissionWrite(String token) throws TException {
- if (authenticated(token)) {
- UserInfo ui = getUserFromToken(token);
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
// log.info("returning LectureListWrite");
return sql.getLectureListPermissionWrite(ui.getUserId());
}
@@ -477,8 +302,8 @@ public class ServerHandler implements Server.Iface {
@Override
public List<Lecture> getLectureListPermissionAdmin(String token) throws TException {
- if (authenticated(token)) {
- UserInfo ui = getUserFromToken(token);
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
// log.info("returning LectureListAdmin");
return sql.getLectureListPermissionAdmin(ui.getUserId());
}
@@ -489,8 +314,8 @@ public class ServerHandler implements Server.Iface {
public boolean updateLecturedata(String name, String newName, String shortdesc, String desc,
String startDate, String endDate, boolean isActive, String imageid, String imageversion,
String token, String Tel, String Fak, String id, String university) throws TException {
- if (authenticated(token)) {
- UserInfo ui = getUserFromToken(token);
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
sql.updateLectureData(imageid, imageversion, ui.getLastName(), newName, desc, shortdesc,
startDate, endDate, isActive, id);
@@ -500,79 +325,59 @@ public class ServerHandler implements Server.Iface {
}
@Override
- public boolean deleteImageServer(String imageid, String imageversion, String token) throws TException {
- if (authenticated(token)) {
- // TODO: Has user permissions to delete this file?
- String stringFile = sql.getFile(imageid, imageversion);
- log.info("File to Delete: " + stringFile);
-
- File tmpFile = new File(Configuration.config.getAbsolute_path() + stringFile);
-
- log.info("Absolute Path used for deletion: " + tmpFile);
-
- try {
- // File wird von Server gelöscht
- FileUtils.forceDelete(tmpFile);
- return true;
+ public boolean deleteImage(String imageId, String imageVersion, String token) throws TException {
+ UserInfo ui = SessionManager.get(token);
+ if (ui == null)
+ return false;
- } catch (IOException e) {
- log.info("Failed to execute deleteImageServer.");
- e.printStackTrace();
+ // TODO: Has user permissions to delete this file?
+ String stringFile = sql.getFile(imageId, imageVersion);
+ if (stringFile == null)
+ return false;
- }
- }
- return false;
- }
-
- @Override
- public boolean deleteImageData(String id, String version, String token) throws TException {
- boolean success = false;
+ log.info("File to Delete: " + stringFile);
- if (authenticated(token)) {
- if (sql.deleteImage(id, version) == true) {
- success = true;
- log.info("Image '" + id + "' and permissions successfully deleted.");
- }
+ if (sql.deleteImage(imageId, imageVersion)) {
+ log.info("Image '" + imageId + "' and permissions successfully deleted.");
}
- return success;
- }
-
- // TODO: ... I can write a small java app that calls this function to delete random files anywhere on the sat
- // If this function is not really required for some obscure reason then it should be removed
- public boolean deleteImageByPath(String image_path) throws TException {
- log.info("File to Delete: " + image_path);
-
- File tmpFile = new File(Configuration.config.getAbsolute_path() + image_path);
+ File tmpFile = new File(Configuration.getVmStoreBasePath(), stringFile);
try {
- // File wird von Server gelöscht
- FileUtils.forceDelete(tmpFile);
- return true;
-
- } catch (IOException e) {
- log.info("Failed to execute deleteImageServer.");
- e.printStackTrace();
-
+ log.info("Absolute Path used for deletion: " + tmpFile.getCanonicalPath());
+ } catch (IOException e1) {
}
- return false;
+ if (tmpFile.isFile()) {
+ log.warn(".... file does not exist!");
+ } else {
+ try {
+ // File wird von Server gelöscht
+ FileUtils.forceDelete(tmpFile);
+ } catch (IOException e) {
+ log.info("Failed to execute deleteImage.", e);
+ }
+ }
+ return true;
}
@Override
public boolean connectedToLecture(String id, String version, String token) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
// TODO: Permissions
return sql.connectedToLecture(id, version);
}
return true;
}
- public boolean deleteLecture(String id, String token, String university) throws TException {
+ @Override
+ public boolean deleteLecture(String id, String token) throws TException {
boolean success = false;
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
// TODO: Permissions
if (sql.deleteLecture(id) == true) {
@@ -586,7 +391,8 @@ public class ServerHandler implements Server.Iface {
@Override
public List<String> getAllUniversities(String token) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
// TODO: Sync with list from master server (.getOrganizations() - call every now and then and add to local DB)
return sql.getAllUniversities();
}
@@ -595,7 +401,8 @@ public class ServerHandler implements Server.Iface {
@Override
public Map<String, String> getLectureData(String lectureid, String token) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getLectureData(lectureid);
}
return null;
@@ -616,7 +423,8 @@ public class ServerHandler implements Server.Iface {
@Override
public boolean checkUser(String username, String token) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.checkUser(username);
}
return false;
@@ -625,9 +433,9 @@ public class ServerHandler implements Server.Iface {
@Override
public boolean createUser(String token, String university) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
// TODO: Do not use university param...
- UserInfo ui = getUserFromToken(token);
String pk_institution = sql.setInstitution(university);
sql.setPerson(ui.getEMail(), ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(),
pk_institution);
@@ -639,8 +447,8 @@ public class ServerHandler implements Server.Iface {
@Override
public boolean writeImageRights(String imageID, String token, String role, String university,
String userID) throws TException {
- if (authenticated(token)) {
- UserInfo ui = getUserFromToken(token);
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
String pk_image = null;
Map<String, String> map = new HashMap<String, String>();
@@ -692,9 +500,8 @@ public class ServerHandler implements Server.Iface {
@Override
public boolean writeLectureRights(String lectureID, String role, String token, String university,
String userID) throws TException {
- if (authenticated(token)) {
- // String pk_lecture = null;
- UserInfo ui = getUserFromToken(token);
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
String pk_institution = sql.setInstitution(university);
String pk_person = sql.setPerson(userID, ui.getLastName(), ui.getFirstName(), ui.getEMail(),
new Date(), pk_institution);
@@ -735,7 +542,8 @@ public class ServerHandler implements Server.Iface {
@Override
public List<Person> getAllOtherSatelliteUsers(List<String> userID, String token) throws TException {
// TODO: Like we couldn't filter the current user on the client side...
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getAllOtherSatelliteUsers(userID);
// return null;
}
@@ -743,19 +551,23 @@ public class ServerHandler implements Server.Iface {
}
// set permissions for users which are !=userID
+ @Override
public boolean writeAdditionalImageRights(String imageID, String userID, boolean isRead, boolean isWrite,
boolean isLinkAllowed, boolean isAdmin, String token) throws TException {
boolean success = false;
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
sql.writeAdditionalImageRights(imageID, userID, isRead, isWrite, isLinkAllowed, isAdmin);
log.info("Written additional image rights for " + userID);
}
return success;
}
+ @Override
public boolean writeAdditionalLectureRights(String lectureID, String userID, boolean isRead,
boolean isWrite, boolean isAdmin, String token) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
sql.writeAdditionalLectureRights(lectureID, userID, isRead, isWrite, isAdmin);
log.info("Written additional lecture rights for " + userID);
@@ -767,15 +579,18 @@ public class ServerHandler implements Server.Iface {
@Override
public List<Person> getPermissionForUserAndImage(String token, String imageID, String userID)
throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getPermissionForUserAndImage(userID, imageID);
}
return null;
}
+ @Override
public List<Person> getPermissionForUserAndLecture(String token, String lectureID, String userID)
throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getPermissionForUserAndLecture(userID, lectureID);
}
return null;
@@ -784,7 +599,8 @@ public class ServerHandler implements Server.Iface {
@Override
public void deleteAllAdditionalImagePermissions(String imageID, String token, String userID)
throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
sql.deleteAllAdditionalImagePermissions(imageID, userID);
}
return;
@@ -793,7 +609,8 @@ public class ServerHandler implements Server.Iface {
@Override
public void deleteAllAdditionalLecturePermissions(String lectureID, String token, String userID)
throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
sql.deleteAllAdditionalLecturePermissions(lectureID, userID);
}
@@ -802,7 +619,8 @@ public class ServerHandler implements Server.Iface {
@Override
public List<Image> getImageList(String userID, String token) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getImageList(userID);
}
return null;
@@ -810,7 +628,8 @@ public class ServerHandler implements Server.Iface {
@Override
public List<String> getAdditionalImageContacts(String imageID, String token) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getAdditionalImageContacts(imageID);
}
return null;
@@ -818,22 +637,17 @@ public class ServerHandler implements Server.Iface {
@Override
public String getOsNameForGuestOs(String guestOS, String token) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getOsNameForGuestOs(guestOS);
}
return null;
}
@Override
- public String createRandomUUID(String token) throws TException {
- if (authenticated(token)) {
- return sql.createRandomUUID();
- }
- return null;
- }
-
public Map<String, String> getItemOwner(String itemID, String token) throws TException {
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.getItemOwner(itemID);
}
return null;
@@ -842,8 +656,8 @@ public class ServerHandler implements Server.Iface {
@Override
public boolean userIsImageAdmin(String imageID, String token, String userID) throws TException {
-
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.userIsImageAdmin(userID, imageID);
}
return false;
@@ -852,8 +666,8 @@ public class ServerHandler implements Server.Iface {
@Override
public boolean userIsLectureAdmin(String userID, String lectureID, String token) throws TException {
-
- if (authenticated(token)) {
+ UserInfo ui = SessionManager.get(token);
+ if (ui != null) {
return sql.userIsLectureAdmin(userID, lectureID);
}
@@ -863,7 +677,7 @@ public class ServerHandler implements Server.Iface {
@Override
public String getInstitutionByID(String institutionID) throws TException {
// TODO Auto-generated method stub
- return null;
+ return "-institution-";
}
@Override
@@ -871,4 +685,59 @@ public class ServerHandler implements Server.Iface {
return Version.VERSION;
}
+ @Override
+ public TransferInformation requestUpload(String userToken, long fileSize, List<ByteBuffer> blockHashes)
+ throws TException {
+ UserInfo ui = SessionManager.get(userToken);
+ if (ui == null)
+ return null;
+
+ String transferToken;
+ try {
+ transferToken = fileServer.createNewUserUpload(ui, fileSize, blockHashes);
+ } catch (Exception e) {
+ log.warn("Cannot accept upload request from user " + Formatter.userFullName(ui), e);
+ if (e instanceof TException)
+ throw (TException) e;
+ throw new TUploadRejectedException(e.getMessage());
+ }
+ return new TransferInformation(transferToken, fileServer.getPlainPort(), fileServer.getSslPort());
+ }
+
+ @Override
+ public void cancelUpload(String uploadToken) throws TException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public TransferInformation requestDownload(String userToken, String imageId) throws TException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public void cancelDownload(String downloadToken) throws TException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public boolean updateImageFile(String uploadToken, String imageId) throws TException {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public boolean authenticated(String token) throws TException {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public boolean setSessionInvalid(String token) throws TException {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
}// end class
diff --git a/dozentenmodulserver/src/main/java/server/SessionManager.java b/dozentenmodulserver/src/main/java/server/SessionManager.java
new file mode 100644
index 00000000..75336de0
--- /dev/null
+++ b/dozentenmodulserver/src/main/java/server/SessionManager.java
@@ -0,0 +1,84 @@
+package server;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.log4j.Logger;
+import org.openslx.imagemaster.thrift.iface.UserInfo;
+import org.openslx.thrifthelper.ThriftManager;
+
+/**
+ * Manages user sessions. Mainly used to map tokens to users.
+ *
+ */
+public class SessionManager {
+
+ private static final Logger LOGGER = Logger.getLogger(SessionManager.class);
+
+ private static class Entry {
+ private static final long SESSION_TIMEOUT = TimeUnit.DAYS.toMillis(1);
+ private final UserInfo user;
+ private long validUntil;
+
+ private Entry(UserInfo user) {
+ this.user = user;
+ this.validUntil = System.currentTimeMillis() + SESSION_TIMEOUT;
+ }
+
+ public void touch(long now) {
+ this.validUntil = now + SESSION_TIMEOUT;
+ }
+ }
+
+ // saves the current tokens and the mapped userdata, returning from the server
+ private static Map<String, Entry> tokenManager = new ConcurrentHashMap<>();
+
+ /**
+ * Get the user corresponding to the given token. Returns null if the token
+ * is not known, or the session already timed out.
+ *
+ * @param token
+ * user's token
+ * @return UserInfo for the matching user
+ */
+ public static UserInfo get(String token) {
+ Entry e = tokenManager.get(token);
+ if (e != null) {
+ // User session already cached
+ final long now = System.currentTimeMillis();
+ if (e.validUntil < now) {
+ tokenManager.remove(token);
+ return getRemote(token);
+ }
+ e.touch(now);
+ return e.user;
+ }
+ return getRemote(token);
+ }
+
+ /**
+ * Remove session matching the given token
+ *
+ * @param token
+ */
+ public static void remove(String token) {
+ tokenManager.remove(token);
+ }
+
+ private static UserInfo getRemote(String token) {
+ UserInfo ui = null;
+ try {
+ ui = ThriftManager.getMasterClient().getUserFromToken(token);
+ } catch (Exception e) {
+ LOGGER.warn("Could not reach master server to query for user token of a client!", e);
+ }
+ if (ui == null)
+ return null;
+ tokenManager.put(token, new Entry(ui));
+ return ui;
+ }
+
+ // TODO: Clean map of old entries periodically
+
+}
diff --git a/dozentenmodulserver/src/main/java/server/StartServer.java b/dozentenmodulserver/src/main/java/server/StartServer.java
index 04314ee7..a5631622 100644
--- a/dozentenmodulserver/src/main/java/server/StartServer.java
+++ b/dozentenmodulserver/src/main/java/server/StartServer.java
@@ -1,59 +1,50 @@
package server;
-import java.io.File;
-import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
+
import models.Configuration;
+
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
-import org.ini4j.InvalidFileFormatException;
-import org.ini4j.Wini;
-import server.BinaryListener;
+import fileserv.FileServer;
public class StartServer {
- /**
- * @param args
- */
-
private static Logger log = Logger.getLogger(StartServer.class);
private static List<Thread> servers = new ArrayList<>();
public static void main(String[] args) {
-
//get going and show basic information in logfile
BasicConfigurator.configure();
- log.info("*************************************************************************************************");
- log.info("******************* " + new Date() + " - starting Application ***********************");
- log.info("*************************************************************************************************");
+ log.info("****************************************************************");
+ log.info("******************* starting Application ***********************");
+ log.info("****************************************************************");
// get Configuration
try {
- log.info(new Date() + " - Getting config from .ini-file");
- Wini ini = new Wini(new File("Server_Config.ini"));
- Configuration.config.setAbsolute_path(ini.get("ftp",
- "path_absolute"));
- Configuration.config
- .setSql_connection(ini.get("sql", "connection"));
- Configuration.config.setSql_pass(ini.get("sql", "pass"));
- Configuration.config.setSql_user(ini.get("sql", "user"));
- } catch (InvalidFileFormatException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
+ log.info("Loading configuration");
+ Configuration.load();
+ } catch (Exception e1) {
+ log.fatal("Could not load configuration", e1);
+ System.exit(1);
+ }
+
+ // Start file transfer server
+ if (!FileServer.instance().start()) {
+ log.error("Could not start internal file server.");
+ return;
}
// Start Server
Thread t;
t = new Thread(new BinaryListener());
servers.add(t);
t.start();
+ // Wait for servers
for (Thread wait : servers) {
boolean success = false;
while (!success) {
diff --git a/dozentenmodulserver/src/main/java/sql/SQL.java b/dozentenmodulserver/src/main/java/sql/SQL.java
index 890e6e39..925ffb57 100644
--- a/dozentenmodulserver/src/main/java/sql/SQL.java
+++ b/dozentenmodulserver/src/main/java/sql/SQL.java
@@ -22,23 +22,26 @@ import org.openslx.sat.thrift.iface.Image;
import org.openslx.sat.thrift.iface.Lecture;
import org.openslx.sat.thrift.iface.Person;
+import util.Util;
+
public class SQL {
private static final Logger log = Logger.getLogger(SQL.class);
- public Connection getConnection() {
- // TODO: Connection pooling, better yet some abstraction layer for mysql, eg. like dalesbred in master-server
+ static {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
-
- e.printStackTrace();
+ log.fatal("Cannot get mysql JDBC driver!", e);
+ System.exit(1);
}
+ }
+
+ public Connection getConnection() {
+ // TODO: Connection pooling, better yet some abstraction layer for mysql, eg. like dalesbred in master-server
try {
- Connection con = DriverManager.getConnection("jdbc:mysql://"
- + Configuration.config.getSql_connection() + "?user="
- + Configuration.config.getSql_user() + "&password=" + Configuration.config.getSql_pass()
- + "");
+ Connection con = DriverManager.getConnection(Configuration.getDbUri(),
+ Configuration.getDbUsername(), Configuration.getDbPassword());
con.setAutoCommit(false);
return con;
@@ -51,50 +54,6 @@ public class SQL {
return null;
}
- public int writeFTPUser(String user, String pass) {
- Statement stm;
- try {
- Connection con = getConnection();
- stm = con.createStatement();
-
- int ret = stm
- .executeUpdate("INSERT INTO `bwLehrpool`.`FtpUsers`(`User`,`Password`,`Uid`,`Gid`,`Dir`)VALUES('"
- + user + "',SHA1('" + pass + "'),'10001','12345','"
- + Configuration.config.getAbsolute_path() + "temp/');");
- con.commit();
- con.close();
- log.info("Created FTPUser " + user + " : " + pass + ".");
- return ret;
- } catch (SQLException e) {
-
- log.info("Failed to writeFTPUser.");
- e.printStackTrace();
- }
- return -1;
- }
-
- public int DeleteUser(String user) {
- try {
- Connection con = getConnection();
-
- String sql = "DELETE FROM `bwLehrpool`.`FtpUsers` where User like ?;";
- PreparedStatement prest = con.prepareStatement(sql);
- prest.setString(1, user);
-
- int ret = prest.executeUpdate();
-
- con.commit();
- con.close();
- log.info("FTPUser " + user + " deleted.");
- return ret;
- } catch (SQLException e) {
-
- log.info("Failed to DeleteUser " + user + ".");
- e.printStackTrace();
- }
- return -1;
- }
-
// no prepared statement to do here
public ResultSet getImage() {
try {
@@ -281,16 +240,11 @@ public class SQL {
return "-1";
}
- public boolean setImageData(String pk_person, boolean license, boolean internet, long cpu, long ram,
- String imagename, String desc, String imagePath, long filesize, String shareMode, String pk_os,
- String uid) {
+ public boolean writeNewImageData(String pk_person, boolean license, boolean internet, String imagename,
+ String desc, String imagePath, long filesize, String shareMode, String pk_os, String imageId) {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- log.info("userID came as pk_person to SQL as: " + pk_person);
- log.info("pk_os is: " + pk_os);
- log.info("uid is: " + uid);
-
int internet_bol = 0;
int license_bol = 0;
if (internet == true) {
@@ -339,7 +293,7 @@ public class SQL {
+ ");";
PreparedStatement prest = con.prepareStatement(sql);
- prest.setString(1, uid);
+ prest.setString(1, imageId);
prest.setString(2, imagename);
prest.setString(3, desc);
prest.setString(4, imagePath);
@@ -350,20 +304,17 @@ public class SQL {
prest.setString(9, pk_os);
prest.setInt(10, license_bol);
prest.setInt(11, internet_bol);
- prest.setLong(12, ram);
- prest.setLong(13, cpu);
+ prest.setLong(12, 2);
+ prest.setLong(13, 2);
prest.setLong(14, filesize);
prest.setString(15, shareMode);
prest.executeUpdate();
con.commit();
- // con.commit();
con.close();
} catch (SQLException e) {
-
- log.info("Failed to setImageData.");
- e.printStackTrace();
- // TODO: Yeah great - it failed, we log it, but we still return true....
+ log.info("Failed to insert new image into DB", e);
+ return false;
}
return true;
@@ -386,12 +337,12 @@ public class SQL {
ResultSet res = prest.executeQuery();
con.commit();
while (res.next()) {
- list.add(new Image(res.getString("GUID_imageID"), res.getString("imageVersion"), res
- .getString("image_name"), res.getString("cond_hasLicenseRestriction"), res
- .getString("name") + " " + res.getString("architecture") + " bit", res
- .getString("lecture"), res.getString("image_update_time"), res.getString("user"), res
- .getString("image_isTemplate"), res.getString("image_description"), res
- .getString("image_filesize")));
+ list.add(new Image(res.getString("GUID_imageID"), res.getString("imageVersion"),
+ res.getString("image_name"), res.getString("cond_hasLicenseRestriction"),
+ res.getString("name") + " " + res.getString("architecture") + " bit",
+ res.getString("lecture"), res.getString("image_update_time"), res.getString("user"),
+ res.getString("image_isTemplate"), res.getString("image_description"),
+ res.getString("image_filesize")));
}
con.close();
} catch (SQLException e) {
@@ -420,12 +371,12 @@ public class SQL {
ResultSet res = prest.executeQuery();
con.commit();
while (res.next()) {
- list.add(new Image(res.getString("GUID_imageID"), res.getString("imageVersion"), res
- .getString("image_name"), res.getString("cond_hasLicenseRestriction"), res
- .getString("name") + " " + res.getString("architecture") + " bit", res
- .getString("lecture"), res.getString("image_update_time"), res.getString("user"), res
- .getString("image_isTemplate"), res.getString("image_description"), res
- .getString("image_filesize")));
+ list.add(new Image(res.getString("GUID_imageID"), res.getString("imageVersion"),
+ res.getString("image_name"), res.getString("cond_hasLicenseRestriction"),
+ res.getString("name") + " " + res.getString("architecture") + " bit",
+ res.getString("lecture"), res.getString("image_update_time"), res.getString("user"),
+ res.getString("image_isTemplate"), res.getString("image_description"),
+ res.getString("image_filesize")));
}
con.close();
} catch (SQLException e) {
@@ -447,16 +398,15 @@ public class SQL {
stm = con.createStatement();
// ResultSet
- ResultSet res = stm
- .executeQuery("SELECT DISTINCT vl.GUID_imageID, vl.imageVersion, vl.image_name, vl.cond_hasLicenseRestriction, vl.image_filesize, os.name, os.architecture, '' as lecture, vl.image_update_time, Concat(u.Nachname,' ',u.Vorname) as user, vl.image_isTemplate, vl.image_description FROM bwLehrpool.pm_VLData_image pmi, bwLehrpool.m_VLData_imageInfo vl, bwLehrpool.m_operatingSystem os, bwLehrpool.m_user u WHERE u.userID = vl.image_owner AND vl.content_operatingSystem = os.operatingSystemID ORDER BY vl.image_name;");
+ ResultSet res = stm.executeQuery("SELECT DISTINCT vl.GUID_imageID, vl.imageVersion, vl.image_name, vl.cond_hasLicenseRestriction, vl.image_filesize, os.name, os.architecture, '' as lecture, vl.image_update_time, Concat(u.Nachname,' ',u.Vorname) as user, vl.image_isTemplate, vl.image_description FROM bwLehrpool.pm_VLData_image pmi, bwLehrpool.m_VLData_imageInfo vl, bwLehrpool.m_operatingSystem os, bwLehrpool.m_user u WHERE u.userID = vl.image_owner AND vl.content_operatingSystem = os.operatingSystemID ORDER BY vl.image_name;");
while (res.next()) {
- list.add(new Image(res.getString("GUID_imageID"), res.getString("imageVersion"), res
- .getString("image_name"), res.getString("cond_hasLicenseRestriction"), res
- .getString("name") + " " + res.getString("architecture") + " bit", res
- .getString("lecture"), res.getString("image_update_time"), res.getString("user"), res
- .getString("image_isTemplate"), res.getString("image_description"), res
- .getString("image_filesize")));
+ list.add(new Image(res.getString("GUID_imageID"), res.getString("imageVersion"),
+ res.getString("image_name"), res.getString("cond_hasLicenseRestriction"),
+ res.getString("name") + " " + res.getString("architecture") + " bit",
+ res.getString("lecture"), res.getString("image_update_time"), res.getString("user"),
+ res.getString("image_isTemplate"), res.getString("image_description"),
+ res.getString("image_filesize")));
}
con.close();
} catch (SQLException e) {
@@ -483,12 +433,12 @@ public class SQL {
ResultSet res = prest.executeQuery();
con.commit();
while (res.next()) {
- list.add(new Image(res.getString("GUID_imageID"), res.getString("imageVersion"), res
- .getString("image_name"), res.getString("cond_hasLicenseRestriction"), res
- .getString("name") + " " + res.getString("architecture") + " bit", res
- .getString("lecture"), res.getString("image_update_time"), res.getString("user"), res
- .getString("image_isTemplate"), res.getString("image_description"), res
- .getString("image_filesize")));
+ list.add(new Image(res.getString("GUID_imageID"), res.getString("imageVersion"),
+ res.getString("image_name"), res.getString("cond_hasLicenseRestriction"),
+ res.getString("name") + " " + res.getString("architecture") + " bit",
+ res.getString("lecture"), res.getString("image_update_time"), res.getString("user"),
+ res.getString("image_isTemplate"), res.getString("image_description"),
+ res.getString("image_filesize")));
}
con.close();
} catch (SQLException e) {
@@ -515,12 +465,12 @@ public class SQL {
ResultSet res = prest.executeQuery();
con.commit();
while (res.next()) {
- list.add(new Image(res.getString("GUID_imageID"), res.getString("imageVersion"), res
- .getString("image_name"), res.getString("cond_hasLicenseRestriction"), res
- .getString("name") + " " + res.getString("architecture") + " bit", res
- .getString("lecture"), res.getString("image_update_time"), res.getString("user"), res
- .getString("image_isTemplate"), res.getString("image_description"), res
- .getString("image_filesize")));
+ list.add(new Image(res.getString("GUID_imageID"), res.getString("imageVersion"),
+ res.getString("image_name"), res.getString("cond_hasLicenseRestriction"),
+ res.getString("name") + " " + res.getString("architecture") + " bit",
+ res.getString("lecture"), res.getString("image_update_time"), res.getString("user"),
+ res.getString("image_isTemplate"), res.getString("image_description"),
+ res.getString("image_filesize")));
}
con.close();
} catch (SQLException e) {
@@ -541,16 +491,15 @@ public class SQL {
stm = con.createStatement();
// ResultSet
- ResultSet res = stm
- .executeQuery("SELECT DISTINCT vl.GUID_imageID, vl.imageVersion, vl.image_name, vl.image_description, vl.cond_hasLicenseRestriction, vl.image_filesize, os.name, os.architecture, '' as lecture, vl.image_update_time, Concat(u.Nachname,' ',u.Vorname) as user, vl.image_isTemplate FROM bwLehrpool.pm_VLData_image pmi, bwLehrpool.m_VLData_imageInfo vl, bwLehrpool.m_operatingSystem os, bwLehrpool.m_user u WHERE vl.image_isTemplate=1 AND vl.content_operatingSystem=os.operatingSystemID AND vl.image_owner=u.userID ORDER BY vl.image_name;");
+ ResultSet res = stm.executeQuery("SELECT DISTINCT vl.GUID_imageID, vl.imageVersion, vl.image_name, vl.image_description, vl.cond_hasLicenseRestriction, vl.image_filesize, os.name, os.architecture, '' as lecture, vl.image_update_time, Concat(u.Nachname,' ',u.Vorname) as user, vl.image_isTemplate FROM bwLehrpool.pm_VLData_image pmi, bwLehrpool.m_VLData_imageInfo vl, bwLehrpool.m_operatingSystem os, bwLehrpool.m_user u WHERE vl.image_isTemplate=1 AND vl.content_operatingSystem=os.operatingSystemID AND vl.image_owner=u.userID ORDER BY vl.image_name;");
while (res.next()) {
- list.add(new Image(res.getString("GUID_imageID"), res.getString("imageVersion"), res
- .getString("image_name"), res.getString("cond_hasLicenseRestriction"), res
- .getString("name") + " " + res.getString("architecture") + " bit", res
- .getString("lecture"), res.getString("image_update_time"), res.getString("user"), res
- .getString("image_isTemplate"), res.getString("image_description"), res
- .getString("image_filesize")));
+ list.add(new Image(res.getString("GUID_imageID"), res.getString("imageVersion"),
+ res.getString("image_name"), res.getString("cond_hasLicenseRestriction"),
+ res.getString("name") + " " + res.getString("architecture") + " bit",
+ res.getString("lecture"), res.getString("image_update_time"), res.getString("user"),
+ res.getString("image_isTemplate"), res.getString("image_description"),
+ res.getString("image_filesize")));
}
con.close();
} catch (SQLException e) {
@@ -577,9 +526,9 @@ public class SQL {
con.commit();
while (res.next()) {
- list.add(new Lecture(res.getString("lectureID"), res.getString("name"), res
- .getString("isActive"), res.getString("startTime"), res.getString("endTime"), res
- .getString("lastUsed"), res.getString("description"), res.getString("image_name"),
+ list.add(new Lecture(res.getString("lectureID"), res.getString("name"),
+ res.getString("isActive"), res.getString("startTime"), res.getString("endTime"),
+ res.getString("lastUsed"), res.getString("description"), res.getString("image_name"),
res.getString("user")));
}
@@ -612,9 +561,9 @@ public class SQL {
con.commit();
while (res.next()) {
- list.add(new Lecture(res.getString("lectureID"), res.getString("name"), res
- .getString("isActive"), res.getString("startTime"), res.getString("endTime"), res
- .getString("lastUsed"), res.getString("description"), res.getString("image_name"),
+ list.add(new Lecture(res.getString("lectureID"), res.getString("name"),
+ res.getString("isActive"), res.getString("startTime"), res.getString("endTime"),
+ res.getString("lastUsed"), res.getString("description"), res.getString("image_name"),
res.getString("user")));
}
@@ -645,9 +594,9 @@ public class SQL {
con.commit();
while (res.next()) {
- list.add(new Lecture(res.getString("lectureID"), res.getString("name"), res
- .getString("isActive"), res.getString("startTime"), res.getString("endTime"), res
- .getString("lastUsed"), res.getString("description"), res.getString("image_name"),
+ list.add(new Lecture(res.getString("lectureID"), res.getString("name"),
+ res.getString("isActive"), res.getString("startTime"), res.getString("endTime"),
+ res.getString("lastUsed"), res.getString("description"), res.getString("image_name"),
res.getString("user")));
}
@@ -667,14 +616,13 @@ public class SQL {
try {
Connection con = getConnection();
Statement stm = con.createStatement();
- ResultSet res = stm
- .executeQuery("SELECT l.lectureID, l.name, l.isActive,l.startTime,l.endTime,l.lastUsed,l.description, i.image_name, concat(u.Nachname,' ',u.Vorname) as user FROM bwLehrpool.m_VLData_lecture l, bwLehrpool.m_VLData_imageInfo i, bwLehrpool.m_user u WHERE i.GUID_imageID=l.imageID and l.admin_owner=u.userID ORDER BY l.name;");
+ ResultSet res = stm.executeQuery("SELECT l.lectureID, l.name, l.isActive,l.startTime,l.endTime,l.lastUsed,l.description, i.image_name, concat(u.Nachname,' ',u.Vorname) as user FROM bwLehrpool.m_VLData_lecture l, bwLehrpool.m_VLData_imageInfo i, bwLehrpool.m_user u WHERE i.GUID_imageID=l.imageID and l.admin_owner=u.userID ORDER BY l.name;");
while (res.next()) {
- list.add(new Lecture(res.getString("lectureID"), res.getString("name"), res
- .getString("isActive"), res.getString("startTime"), res.getString("endTime"), res
- .getString("lastUsed"), res.getString("description"), res.getString("image_name"),
+ list.add(new Lecture(res.getString("lectureID"), res.getString("name"),
+ res.getString("isActive"), res.getString("startTime"), res.getString("endTime"),
+ res.getString("lastUsed"), res.getString("description"), res.getString("image_name"),
res.getString("user")));
}
@@ -697,8 +645,7 @@ public class SQL {
try {
Connection con = getConnection();
Statement stm = con.createStatement();
- ResultSet rs = stm
- .executeQuery("SELECT name, architecture FROM bwLehrpool.m_operatingSystem ORDER BY name, architecture;");
+ ResultSet rs = stm.executeQuery("SELECT name, architecture FROM bwLehrpool.m_operatingSystem ORDER BY name, architecture;");
while (rs.next()) {
list.add(rs.getString("name") + " " + rs.getString("architecture") + " bit");
}
@@ -974,14 +921,11 @@ public class SQL {
return null;
}
- public int UpdateImageData(String name, String newName, String desc, String image_path, boolean license,
- boolean internet, long cpu, long ram, String id, String version, boolean isTemplate,
- long filesize, String shareMode, String ospk) {
+ public boolean updateImageData(String newName, String desc, boolean license, boolean internet,
+ String imageId, String shareMode, String ospk) {
try {
Connection con = getConnection();
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- // Statement stm = con.createStatement();
- int newVersion = Integer.parseInt(version) + 1;
int internet_bol = 0;
int license_bol = 0;
@@ -994,8 +938,8 @@ public class SQL {
license_bol = 1;
}
- String sql = "UPDATE bwLehrpool.m_VLData_imageInfo SET imageVersion = " + "?" + ",image_name = "
- + "?" + ",image_description = " + "?" + " ,image_path = " + "?"
+ String sql = "UPDATE bwLehrpool.m_VLData_imageInfo SET " + "imageVersion = " + "?" + ", "
+ + "image_name = " + "?" + ",image_description = " + "?"
+ " ,image_update_time = '"
+ formatter.format(new Date())
+ "' ,rec_change_time = '"
@@ -1009,32 +953,25 @@ public class SQL {
+ " ,cond_minCPUs = "
+ "?"
+ " ,image_isTemplate = "
- // + isTemplate
+ "0 "
+ ",content_operatingSystem = "
+ "?"
- + ",image_filesize = "
- + "?"
+ ",image_syncMode = "
+ "?"
- + " WHERE GUID_imageID = "
- + "?"
- + " AND imageVersion = " + "?" + ";";
+ + " WHERE GUID_imageID = " + "?" + " AND imageVersion = " + "?" + ";";
PreparedStatement prest = con.prepareStatement(sql);
- prest.setInt(1, newVersion);
+ prest.setInt(1, 1);
prest.setString(2, newName);
prest.setString(3, desc);
- prest.setString(4, image_path);
- prest.setInt(5, license_bol);
- prest.setInt(6, internet_bol);
- prest.setLong(7, ram);
- prest.setLong(8, cpu);
- prest.setString(9, ospk);
- prest.setLong(10, filesize);
- prest.setString(11, shareMode);
- prest.setString(12, id);
- prest.setString(13, version);
+ prest.setInt(4, license_bol);
+ prest.setInt(5, internet_bol);
+ prest.setLong(6, 2);
+ prest.setLong(7, 2);
+ prest.setString(8, ospk);
+ prest.setString(9, shareMode);
+ prest.setString(10, imageId);
+ prest.setString(11, "1");
prest.executeUpdate();
@@ -1042,13 +979,13 @@ public class SQL {
// con.commit();
con.close();
- return 0;
+ return true;
} catch (SQLException e) {
log.info("Failed to UpdateImageData.");
e.printStackTrace();
}
- return -1;
+ return false;
}
public boolean deleteImage(String id, String version) {
@@ -1183,9 +1120,11 @@ public class SQL {
}
public String getFile(String imageid, String imageversion) {
+ String path = null;
+ Connection con = null;
try {
- Connection con = getConnection();
+ con = getConnection();
String sql = "SELECT image_path FROM bwLehrpool.m_VLData_imageInfo WHERE GUID_imageID = " + "?"
+ " AND imageVersion = " + "?" + ";";
@@ -1197,15 +1136,15 @@ public class SQL {
ResultSet rs = prest.executeQuery();
con.commit();
- rs.next();
- String path = rs.getString("image_path");
- con.close();
+ if (rs.next())
+ path = rs.getString("image_path");
+
return path;
} catch (SQLException e) {
-
- log.info("Failed to getFile.");
- e.printStackTrace();
+ log.info("Failed to getFile.", e);
+ } finally {
+ Util.safeClose(con);
}
return null;
@@ -1486,8 +1425,8 @@ public class SQL {
while (res.next()) {
// fill the list with users - permissions are all false because
// the image is new
- list.add(new Person(res.getString("userID"), res.getString("Nachname"), res
- .getString("Vorname"), res.getString("mail"), false, false, false, false, false,
+ list.add(new Person(res.getString("userID"), res.getString("Nachname"),
+ res.getString("Vorname"), res.getString("mail"), false, false, false, false, false,
false, false));
}
} catch (SQLException e) {
@@ -1550,9 +1489,9 @@ public class SQL {
// fill the list with users - permissions are all false because
// the image is new
- list.add(new Person(res.getString("userID"), res.getString("Nachname"), res
- .getString("Vorname"), res.getString("mail"), image_read, image_write, link_allowed,
- image_admin, false, // lecture_read
+ list.add(new Person(res.getString("userID"), res.getString("Nachname"),
+ res.getString("Vorname"), res.getString("mail"), image_read, image_write,
+ link_allowed, image_admin, false, // lecture_read
false, // lecture_write
false) // lecture_admin
);
@@ -1611,8 +1550,8 @@ public class SQL {
// fill the list with users - permissions are all false because
// the image is new
- list.add(new Person(res.getString("userID"), res.getString("Nachname"), res
- .getString("Vorname"), res.getString("mail"), false, // image read
+ list.add(new Person(res.getString("userID"), res.getString("Nachname"),
+ res.getString("Vorname"), res.getString("mail"), false, // image read
false, // image write
false, // image link
false, // image admin
diff --git a/dozentenmodulserver/src/main/java/thrift/MasterThriftConnection.java b/dozentenmodulserver/src/main/java/thrift/MasterThriftConnection.java
deleted file mode 100644
index a921e65f..00000000
--- a/dozentenmodulserver/src/main/java/thrift/MasterThriftConnection.java
+++ /dev/null
@@ -1,43 +0,0 @@
-package thrift;
-
-import org.apache.log4j.Logger;
-import org.apache.thrift.protocol.TBinaryProtocol;
-import org.apache.thrift.protocol.TProtocol;
-import org.apache.thrift.transport.TFramedTransport;
-import org.apache.thrift.transport.TSocket;
-import org.apache.thrift.transport.TTransport;
-import org.apache.thrift.transport.TTransportException;
-import org.openslx.imagemaster.thrift.iface.ImageServer.Client;
-
-public class MasterThriftConnection {
-
- private final static Logger LOGGER = Logger.getLogger(MasterThriftConnection.class);
-
- public static final String MASTERSERVER_IP = "132.230.4.16";
- public static final int MASTERSERVER_PORT = 9090;
- public static final int MASTERSERVER_TIMEOUT_MS = 6000;
-
- final TTransport transport = new TFramedTransport(new TSocket(
- MASTERSERVER_IP, MASTERSERVER_PORT, MASTERSERVER_TIMEOUT_MS));
-
- public Client getMasterThriftConnection() {
-
- try {
- transport.open();
- } catch (TTransportException e) {
- LOGGER.error("Keine Verbindung möglich!");
- return null;
- }
-
- final TProtocol protocol = new TBinaryProtocol(transport);
- final Client client = new Client(protocol);
- //LOGGER.info("Masterserver '" + MASTERSERVER_IP + "' erreichbar.");
-
- return client;
- }
-
- public void closeMasterThriftConnection() {
- transport.close();
- }
-}
- \ No newline at end of file
diff --git a/dozentenmodulserver/src/main/java/thrift/SessionData.java b/dozentenmodulserver/src/main/java/thrift/SessionData.java
deleted file mode 100644
index c862bcfa..00000000
--- a/dozentenmodulserver/src/main/java/thrift/SessionData.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package thrift;
-
-public class SessionData {
-
- private String sessionID;
- private String authToken;
- private String serverAdress;
-
- public static SessionData session =new SessionData();
-
- public String getSessionID() {
- return sessionID;
- }
- public void setSessionID(String sessionID) {
- this.sessionID = sessionID;
- }
- public String getAuthToken() {
- return authToken;
- }
- public void setAuthToken(String authToken) {
- this.authToken = authToken;
- }
- public String getServerAdress() {
- return serverAdress;
- }
- public void setServerAdress(String serverAdress) {
- this.serverAdress = serverAdress;
- }
-
-
-
-}
- \ No newline at end of file
diff --git a/dozentenmodulserver/src/main/java/thrift/ThriftConnection.java b/dozentenmodulserver/src/main/java/thrift/ThriftConnection.java
deleted file mode 100644
index 65a905bb..00000000
--- a/dozentenmodulserver/src/main/java/thrift/ThriftConnection.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package thrift;
-
-import javax.swing.JOptionPane;
-
-import org.apache.thrift.protocol.TBinaryProtocol;
-import org.apache.thrift.protocol.TProtocol;
-import org.apache.thrift.transport.TSocket;
-import org.apache.thrift.transport.TTransport;
-import org.apache.thrift.transport.TTransportException;
-import org.openslx.sat.thrift.iface.Server;
-import org.openslx.sat.thrift.iface.Server.Client;
-//import models.SessionData;
-import org.apache.log4j.Logger;
-
-public class ThriftConnection {
-
- private final static Logger LOGGER = Logger.getLogger(ThriftConnection.class);
-
- private String satAddress = ""+SessionData.session.getServerAdress();
- final TTransport transport = new TSocket(satAddress, 9090);
-
- public ThriftConnection() {
- // TODO Auto-generated constructor stub
- }
-
- public Client getThriftConnection()
- {
-
- try {
- transport.open();
- } catch (TTransportException e) {
- LOGGER.error("Keine Verbindung möglich! Satellit: " + satAddress);
- e.printStackTrace();
- JOptionPane.showMessageDialog(null,
- "Konnte keine Verbindung zum Satellit '" + satAddress + "' aufbauen!",
- "Debug-Message", JOptionPane.ERROR_MESSAGE);
- return null;
- }
-
- final TProtocol protocol = new TBinaryProtocol(transport);
-
- final Server.Client client = new Server.Client(protocol);
- LOGGER.info("Verbindung zu "+satAddress+" wurde aufgebaut.");
-
- return client;
- }
-
- public void closeThriftConnection()
- {
- LOGGER.info("Verbindung wird geplant getrennt.");
- transport.close();
- }
-}
- \ No newline at end of file
diff --git a/dozentenmodulserver/src/main/java/util/Constants.java b/dozentenmodulserver/src/main/java/util/Constants.java
new file mode 100644
index 00000000..8ac5dabd
--- /dev/null
+++ b/dozentenmodulserver/src/main/java/util/Constants.java
@@ -0,0 +1,21 @@
+package util;
+
+import fileserv.FileChunk;
+
+public class Constants {
+ public static final String INCOMPLETE_UPLOAD_SUFFIX = ".part";
+ public static final int MAX_UPLOADS;
+
+ static {
+ long maxMem = Runtime.getRuntime().maxMemory();
+ if (maxMem == Long.MAX_VALUE) {
+ // Apparently the JVM was started without a memory limit (no -Xmx cmdline),
+ // so we assume a default of 256MB
+ maxMem = 256l * 1024l * 1024l;
+ }
+ maxMem /= 1024l * 1024l;
+ // Now maxMem is the amount of memory in MiB
+
+ MAX_UPLOADS = (int) Math.max(1, (maxMem - 64) / (FileChunk.CHUNK_SIZE_MIB + 1));
+ }
+}
diff --git a/dozentenmodulserver/src/main/java/util/FileSystem.java b/dozentenmodulserver/src/main/java/util/FileSystem.java
new file mode 100644
index 00000000..5f5a1e08
--- /dev/null
+++ b/dozentenmodulserver/src/main/java/util/FileSystem.java
@@ -0,0 +1,25 @@
+package util;
+
+import java.io.File;
+
+import org.apache.log4j.Logger;
+
+public class FileSystem {
+
+ private static final Logger LOGGER = Logger.getLogger(FileSystem.class);
+
+ public static String getRelativePath(File absolutePath, File parentDir) {
+ String file;
+ String dir;
+ try {
+ file = absolutePath.getCanonicalPath();
+ dir = parentDir.getCanonicalPath() + File.separator;
+ } catch (Exception e) {
+ LOGGER.error("Could not get relative path for " + absolutePath.toString(), e);
+ return null;
+ }
+ if (!file.startsWith(dir))
+ return null;
+ return file.substring(dir.length());
+ }
+}
diff --git a/dozentenmodulserver/src/main/java/util/Formatter.java b/dozentenmodulserver/src/main/java/util/Formatter.java
new file mode 100644
index 00000000..5c5982fb
--- /dev/null
+++ b/dozentenmodulserver/src/main/java/util/Formatter.java
@@ -0,0 +1,59 @@
+package util;
+
+import java.io.File;
+import java.util.UUID;
+
+import models.Configuration;
+
+import org.joda.time.format.DateTimeFormat;
+import org.joda.time.format.DateTimeFormatter;
+import org.openslx.imagemaster.thrift.iface.UserInfo;
+
+public class Formatter {
+
+ private static final DateTimeFormatter vmNameDateFormat = DateTimeFormat.forPattern("dd_HH-mm-ss");
+
+ /**
+ * Generate a unique file name used for a virtual machine
+ * image that is currently uploading.
+ *
+ * @return Absolute path name of file
+ */
+ public static File getTempImageName() {
+ return new File(Configuration.getCurrentVmStorePath(), UUID.randomUUID().toString()
+ + Constants.INCOMPLETE_UPLOAD_SUFFIX);
+ }
+
+ /**
+ * Generate a file name for the given VM based on owner and display name.
+ *
+ * @param user The user associated with the VM, e.g. the owner
+ * @param imageName Name of the VM
+ * @return File name for the VM derived from the function's input
+ */
+ public static String vmName(UserInfo user, String imageName) {
+ return cleanFileName(vmNameDateFormat.print(System.currentTimeMillis()) + "_" + user.lastName + "_"
+ + imageName);
+ }
+
+ /**
+ * Make sure file name contains only a subset of ascii characters and is not
+ * too long.
+ *
+ * @param name What we want to turn into a file name
+ * @return A sanitized form of name that should be safe to use as a file
+ * name
+ */
+ public static String cleanFileName(String name) {
+ if (name == null)
+ return "null";
+ name = name.replaceAll("[^a-zA-Z0-9_\\.\\-]+", "_");
+ if (name.length() > 120)
+ name = name.substring(0, 120);
+ return name;
+ }
+
+ public static String userFullName(UserInfo ui) {
+ return ui.firstName + " " + ui.lastName;
+ }
+}
diff --git a/dozentenmodulserver/src/main/java/util/Util.java b/dozentenmodulserver/src/main/java/util/Util.java
new file mode 100644
index 00000000..28f522b8
--- /dev/null
+++ b/dozentenmodulserver/src/main/java/util/Util.java
@@ -0,0 +1,45 @@
+package util;
+
+import java.io.Closeable;
+
+public class Util {
+
+ /**
+ * Try to close everything passed to this method. Never throw an exception
+ * if it fails, just silently continue.
+ *
+ * @param item One or more objects that are Closeable
+ */
+ public static void safeClose(Closeable... item) {
+ if (item == null)
+ return;
+ for (Closeable c : item) {
+ if (c == null)
+ continue;
+ try {
+ c.close();
+ } catch (Exception e) {
+ }
+ }
+ }
+
+ /**
+ * Try to close everything passed to this method. Never throw an exception
+ * if it fails, just silently continue.
+ *
+ * @param item One or more objects that are AutoCloseable
+ */
+ public static void safeClose(AutoCloseable... item) {
+ if (item == null)
+ return;
+ for (AutoCloseable c : item) {
+ if (c == null)
+ continue;
+ try {
+ c.close();
+ } catch (Exception e) {
+ }
+ }
+ }
+
+}