diff options
author | Simon Rettberg | 2014-04-24 18:59:35 +0200 |
---|---|---|
committer | Simon Rettberg | 2014-04-24 18:59:35 +0200 |
commit | ed787b6f67954faab790cab107503eac8e6aad3c (patch) | |
tree | 6f05300170e670ab5db0ccda62bb918d0371b7ad | |
parent | Fix name of format style (diff) | |
parent | Add FTPS to MasterFtpServer (diff) | |
download | masterserver-ed787b6f67954faab790cab107503eac8e6aad3c.tar.gz masterserver-ed787b6f67954faab790cab107503eac8e6aad3c.tar.xz masterserver-ed787b6f67954faab790cab107503eac8e6aad3c.zip |
Merge branch 'master' of dnbd3:bwlp/masterserver
28 files changed, 897 insertions, 610 deletions
@@ -8,4 +8,5 @@ /src/main/java/org/openslx/imagemaster/thrift/iface /gen-java /src/main/properties/ftp.properties +/config/keystore.jks diff --git a/config/global.properties.example b/config/global.properties.example index e2e1a3b..0b26f75 100644 --- a/config/global.properties.example +++ b/config/global.properties.example @@ -1,15 +1,15 @@ # fill in properties and rename to global.properties ##################### -# Directories # +# Main # ##################### -# the base dir of the ftp server (should exists) -ftp_base_dir=/tmp - # the dir where the images are stored image_dir=/tmp +# keystore (.jks format) +keystore=./config/keystore.jks + ##################### # LDAP data # ##################### @@ -31,4 +31,27 @@ ldap_search_base_dn=ou\=people,dc\=uni-freiburg,dc\=de # search filter (use a % for the username replacement -ldap_search_filter=(&(objectclass\=person)(uid\=%))
\ No newline at end of file +ldap_search_filter=(&(objectclass\=person)(uid\=%)) + +##################### +# Session # +##################### + +# session timeout for users (in seconds) +session_timeout_user=600 + +# session timeout for servers (in seconds) +session_timeout_server=600 + +##################### +# FTP Server # +##################### + +# the base dir of the ftp server (should exists) +ftp_base_dir=/tmp + +# the port of the ftp server +ftp_port=2221 + +# timeout for kicking ftp users (in minutes) +ftp_timeout=60
\ No newline at end of file diff --git a/src/main/java/org/openslx/imagemaster/App.java b/src/main/java/org/openslx/imagemaster/App.java index 8d7f200..85ec50b 100644 --- a/src/main/java/org/openslx/imagemaster/App.java +++ b/src/main/java/org/openslx/imagemaster/App.java @@ -1,80 +1,73 @@ package org.openslx.imagemaster; -import java.io.BufferedInputStream; -import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; +import org.openslx.imagemaster.Globals.PropInt; import org.openslx.imagemaster.server.FtpCredentialsScheduler; +import org.openslx.imagemaster.server.MasterFtpServer; import org.openslx.imagemaster.thrift.server.BinaryListener; -public class App { - private static Logger log = Logger.getLogger(App.class); +public class App +{ + + private static Logger log = Logger.getLogger( App.class ); private static List<Thread> servers = new ArrayList<>(); + + public static final MasterFtpServer ftpServer = new MasterFtpServer(); - public static void main(String[] args) { + public static void main( String[] args ) + { // Init logging - log.info("Starting Application"); + log.info( "Starting Application" ); // Load properties - boolean error = false; - BufferedInputStream stream = null; try { - stream = new BufferedInputStream(new FileInputStream( - "config/global.properties")); - Globals.properties.load(stream); - if (!Globals.propertiesValid()) { - log.error("Config file contains errors."); - System.exit(1); - } - } catch (IOException e) { - log.error("Could not load config file. Quitting."); - error = true; - } finally { - if (stream != null) { - try { - stream.close(); - } catch (IOException e) { - } + Globals.loadProperties(); // don't need to check return, because this should be the first time where props are loaded. + if ( !Globals.propertiesValid() ) { + log.error( "Config file contains errors." ); + System.exit( 1 ); } - if (error) - System.exit(1); - log.info("Loaded config file"); + } catch ( IOException e ) { + log.error( "Could not load config file. Quitting." ); + System.exit( 1 ); } + log.info( "Loaded config file" ); // Create binary listener Thread t; - t = new Thread(new BinaryListener(), "BinaryListener"); - servers.add(t); + t = new Thread( new BinaryListener(), "BinaryListener" ); + servers.add( t ); t.start(); // Create Ftp Server + ftpServer.init( Globals.getPropertyInt( PropInt.FTPPORT ) ); Thread f; - f = new Thread(Globals.ftpServer, "FtpServer"); - servers.add(f); + f = new Thread( ftpServer, "FtpServer" ); + servers.add( f ); f.start(); - + // start FtpCredentialsScheduler FtpCredentialsScheduler.startScheduling(); - + // Run more servers // ... // Wait for all servers to die - for (Thread wait : servers) { + for ( Thread wait : servers ) { boolean success = false; - while (!success) { + while ( !success ) { try { wait.join(); success = true; - } catch (InterruptedException e) { + } catch ( InterruptedException e ) { // Do nothing... } } } - - log.info("All Servers shut down, exiting..."); + + log.info( "All Servers shut down, exiting..." ); } } diff --git a/src/main/java/org/openslx/imagemaster/Globals.java b/src/main/java/org/openslx/imagemaster/Globals.java index 7dbbae4..717cb1e 100644 --- a/src/main/java/org/openslx/imagemaster/Globals.java +++ b/src/main/java/org/openslx/imagemaster/Globals.java @@ -1,66 +1,186 @@ package org.openslx.imagemaster; +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.IOException; import java.util.Properties; import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; import org.openslx.imagemaster.server.MasterFtpServer; -public class Globals { - public static final Properties properties = new Properties(); - - public static final MasterFtpServer ftpServer = new MasterFtpServer(2221, "admin", - "SI*HoZCC!]V)p>B2", Globals.properties.getProperty("ftp_base_dir")); - - // properties - public static final String ftpBaseDir = "ftp_base_dir"; - public static final String imageDir = "image_dir"; - public static final String ldapPort = "ldap_port"; - public static final String ldapHost = "ldap_host"; - public static final String ldapSsl = "ldap_ssl"; - public static final String ldapBindQuery = "ldap_bind_query"; - public static final String ldapSearchBaseDn = "ldap_search_base_dn"; - public static final String ldapSearchFilter = "ldap_search_filter"; - - public static boolean propertiesValid() { - if (Globals.properties.getProperty(ftpBaseDir) == null - || Globals.properties.getProperty(ftpBaseDir).isEmpty() - || Globals.properties.getProperty(imageDir) == null - || Globals.properties.getProperty(imageDir).isEmpty() - || Globals.properties.getProperty(ldapPort) == null - || Globals.properties.getProperty(ldapPort).isEmpty() - || Globals.properties.getProperty(ldapHost) == null - || Globals.properties.getProperty(ldapHost).isEmpty() - || Globals.properties.getProperty(ldapSsl) == null - || Globals.properties.getProperty(ldapSsl).isEmpty() - || Globals.properties.getProperty(ldapBindQuery) == null - || Globals.properties.getProperty(ldapBindQuery).isEmpty() - || Globals.properties.getProperty(ldapSearchBaseDn) == null - || Globals.properties.getProperty(ldapSearchBaseDn).isEmpty() - || Globals.properties.getProperty(ldapSearchFilter) == null - || Globals.properties.getProperty(ldapSearchFilter).isEmpty() - ) { +public class Globals +{ + + private static Logger log = Logger.getLogger( Globals.class ); + private static final Properties properties = new Properties(); + private static boolean loadedProperties = false; + + public static enum PropInt + { + LDAPPORT, SESSIONTIMEOUTUSER, SESSIONTIMEOUTSERVER, FTPPORT, FTPTIMEOUT + } + + public static enum PropString + { + IMAGEDIR, KEYSTORE, LDAPHOST, LDAPBINDQUERY, LDAPSEARCHBASEDN, LDAPSEARCHFILTER, FTPBASEDIR + } + + public static enum PropBool + { + LDAPSSL + } + + /** + * Loads the properties from config/global.properties + * + * @return if the properties were loaded or not + * @throws IOException + */ + public static boolean loadProperties() throws IOException + { + if ( loadedProperties ) + return false; + + // Load properties + BufferedInputStream stream = new BufferedInputStream( new FileInputStream( "config/global.properties" ) ); + properties.load( stream ); + stream.close(); + + return true; + } + + public static boolean propertiesValid() + { + if ( Globals.getPropertyString( PropString.IMAGEDIR ) == null + || Globals.getPropertyString( PropString.IMAGEDIR ).isEmpty() + || Globals.getPropertyString( PropString.LDAPHOST ) == null + || Globals.getPropertyString( PropString.LDAPHOST ).isEmpty() + || Globals.getPropertyString( PropString.LDAPBINDQUERY ) == null + || Globals.getPropertyString( PropString.LDAPBINDQUERY ).isEmpty() + || Globals.getPropertyString( PropString.LDAPSEARCHBASEDN ) == null + || Globals.getPropertyString( PropString.LDAPSEARCHBASEDN ).isEmpty() + || Globals.getPropertyString( PropString.LDAPSEARCHFILTER ) == null + || Globals.getPropertyString( PropString.LDAPSEARCHFILTER ).isEmpty() + || Globals.getPropertyString( PropString.FTPBASEDIR ) == null + || Globals.getPropertyString( PropString.FTPBASEDIR ).isEmpty() + || Globals.getPropertyString( PropString.KEYSTORE ) == null + || Globals.getPropertyString( PropString.KEYSTORE ).isEmpty() + + || Globals.getPropertyInt( PropInt.LDAPPORT ) == 0 + || Globals.getPropertyInt( PropInt.SESSIONTIMEOUTUSER ) == 0 + || Globals.getPropertyInt( PropInt.SESSIONTIMEOUTSERVER ) == 0 + || Globals.getPropertyInt( PropInt.FTPPORT ) == 0 + || Globals.getPropertyInt( PropInt.FTPTIMEOUT ) == 0 ) { return false; } - - if (StringUtils.countMatches(Globals.properties.getProperty(ldapBindQuery), "%") != 1) { + + // check ldap_bind_query + if ( StringUtils.countMatches( Globals.getPropertyString( PropString.LDAPBINDQUERY ), "%" ) != 1 ) { + log.error( "ldap_bind_query does not contain '%'" ); return false; } - - if (StringUtils.countMatches(Globals.properties.getProperty(ldapSearchFilter), "%") != 1) { + + // check ldap_search_filter + if ( StringUtils.countMatches( Globals.getPropertyString( PropString.LDAPSEARCHFILTER ), "%" ) != 1 ) { + log.error( "ldap_search_filter does not contain '%'" ); return false; } - // remove "/" at the end of the path - String ftp = Globals.properties.getProperty(ftpBaseDir); - if (ftp.endsWith("/")) { - Globals.properties.put(ftpBaseDir, ftp.substring(0, ftp.length() - 1)); + // check keystore + if ( !Globals.getPropertyString( PropString.KEYSTORE ).endsWith( ".jks" )) { + log.error( "Keystore is not in jks format." ); + return false; } - - String image = Globals.properties.getProperty(imageDir); - if (image.endsWith("/")) { - Globals.properties.put(imageDir, image.substring(0, image.length() -1 )); + + // remove "/" at the end of the paths + String ftp = Globals.getPropertyString( PropString.FTPBASEDIR ); + if ( ftp.endsWith( "/" ) ) { + Globals.properties.put( "ftp_base_dir", ftp.substring( 0, ftp.length() - 1 ) ); } - + + String image = Globals.getPropertyString( PropString.IMAGEDIR ); + if ( image.endsWith( "/" ) ) { + Globals.properties.put( "image_dir", image.substring( 0, image.length() - 1 ) ); + } + return true; } + + public static int getPropertyInt( Globals.PropInt props ) + { + String result = null; + + switch ( props ) { + case LDAPPORT: + result = properties.getProperty( "ldap_port" ); + break; + case SESSIONTIMEOUTUSER: + result = properties.getProperty( "session_timeout_user" ); + break; + case SESSIONTIMEOUTSERVER: + result = properties.getProperty( "session_timeout_server" ); + break; + case FTPPORT: + result = properties.getProperty( "ftp_port" ); + break; + case FTPTIMEOUT: + result = properties.getProperty( "ftp_timeout" ); + break; + default: + result = "0"; + break; + } + + if ( result == null ) + return 0; + + return Integer.valueOf( result ); + } + + public static String getPropertyString( Globals.PropString props ) + { + String result = null; + + switch ( props ) { + case IMAGEDIR: + result = properties.getProperty( "image_dir" ); + break; + case LDAPHOST: + result = properties.getProperty( "ldap_host" ); + break; + case LDAPBINDQUERY: + result = properties.getProperty( "ldap_bind_query" ); + break; + case LDAPSEARCHBASEDN: + result = properties.getProperty( "ldap_search_base_dn" ); + break; + case LDAPSEARCHFILTER: + result = properties.getProperty( "ldap_search_filter" ); + break; + case FTPBASEDIR: + result = properties.getProperty( "ftp_base_dir" ); + break; + default: + result = ""; + break; + } + + return result; + } + + public static boolean getPropertyBool( Globals.PropBool props ) + { + String result = null; + + switch ( props ) { + case LDAPSSL: + result = properties.getProperty( "ldap_ssl" ); + default: + result = ""; + break; + } + + return Boolean.valueOf( result ); + } } diff --git a/src/main/java/org/openslx/imagemaster/db/DbImage.java b/src/main/java/org/openslx/imagemaster/db/DbImage.java index d3e8a94..bf643bb 100644 --- a/src/main/java/org/openslx/imagemaster/db/DbImage.java +++ b/src/main/java/org/openslx/imagemaster/db/DbImage.java @@ -5,10 +5,13 @@ import java.util.Date; import org.openslx.imagemaster.thrift.iface.ImageData; -public class DbImage { +public class DbImage +{ + private String UUID; - public DbImage(String UUID) { + public DbImage(String UUID) + { this.UUID = UUID; } @@ -18,37 +21,42 @@ public class DbImage { * @param imageData * @return */ - public static boolean exists(ImageData imageData) { - if (MySQL.findUniqueOrNull(DbImage.class, + public static boolean exists( ImageData imageData ) + { + if ( MySQL.findUniqueOrNull( DbImage.class, "SELECT images.UUID FROM images WHERE images.UUID = ?", - imageData.uuid) == null) { + imageData.uuid ) == null ) { return false; } else { return true; } } - public static int insert(ImageData imageData) { - Date createTime = new Date(imageData.imageCreateTime); - Date updateTime = new Date(imageData.imageUpdateTime); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - int ownerId = DbUser.getUserIdByName(imageData.imageOwner); - - return MySQL.update( - "INSERT INTO images (UUID, image_version, image_name, image_path, image_createTime, image_updateTime, image_owner, content_operatingSystem, status_isValid, status_isDeleted, image_shortDescription, image_longDescription) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - imageData.uuid, imageData.imageVersion, imageData.imageName, "!uploading!", - sdf.format(createTime), sdf.format(updateTime), ownerId, - imageData.conentOperatingSystem, imageData.statusIsValid, - imageData.statusIsDeleted, imageData.imageShortDescription, - imageData.imageLongDescription); + public static int insert( ImageData imageData ) + { + Date createTime = new Date( imageData.imageCreateTime ); + Date updateTime = new Date( imageData.imageUpdateTime ); + SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); + + int ownerId = DbUser.getUserIdByName( imageData.imageOwner ); + + return MySQL + .update( + "INSERT INTO images (UUID, image_version, image_name, image_path, image_createTime, image_updateTime, image_owner, content_operatingSystem, status_isValid, status_isDeleted, image_shortDescription, image_longDescription) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + imageData.uuid, imageData.imageVersion, imageData.imageName, "!uploading!", + sdf.format( createTime ), sdf.format( updateTime ), ownerId, + imageData.conentOperatingSystem, imageData.statusIsValid, + imageData.statusIsDeleted, imageData.imageShortDescription, + imageData.imageLongDescription ); } - public String getUUID() { + public String getUUID() + { return this.UUID; } - public static int update(ImageData imageData, String location) { - return MySQL.update("UPDATE images SET images.image_path = ? WHERE images.UUID = ?", location, imageData.uuid); + public static int update( ImageData imageData, String location ) + { + return MySQL.update( "UPDATE images SET images.image_path = ? WHERE images.UUID = ?", location, imageData.uuid ); } } diff --git a/src/main/java/org/openslx/imagemaster/db/DbSatellite.java b/src/main/java/org/openslx/imagemaster/db/DbSatellite.java index 7e9ef54..9f3cd01 100644 --- a/src/main/java/org/openslx/imagemaster/db/DbSatellite.java +++ b/src/main/java/org/openslx/imagemaster/db/DbSatellite.java @@ -1,32 +1,39 @@ package org.openslx.imagemaster.db; -public class DbSatellite { +public class DbSatellite +{ + private String organization, address, name; // needs to be public in order to be found by MySQL - public DbSatellite(String organization, String address, String name) { + public DbSatellite(String organization, String address, String name) + { this.organization = organization; this.address = address; this.name = name; } - public static DbSatellite fromOrganization(String organization) { + public static DbSatellite fromOrganization( String organization ) + { return MySQL .findUniqueOrNull( DbSatellite.class, "SELECT satellite.organization, satellite.address, satellite.name FROM satellite WHERE satellite.organization = ? LIMIT 1", - organization); + organization ); } - public String getAddress() { + public String getAddress() + { return address; } - public String getName() { + public String getName() + { return name; } - public String getOrganization() { + public String getOrganization() + { return organization; } -}
\ No newline at end of file +} diff --git a/src/main/java/org/openslx/imagemaster/db/DbUser.java b/src/main/java/org/openslx/imagemaster/db/DbUser.java index 774917d..45cbb2a 100644 --- a/src/main/java/org/openslx/imagemaster/db/DbUser.java +++ b/src/main/java/org/openslx/imagemaster/db/DbUser.java @@ -3,27 +3,31 @@ package org.openslx.imagemaster.db; import org.apache.log4j.Logger; import org.openslx.imagemaster.session.User; -public class DbUser extends User { +public class DbUser extends User +{ + private static Logger log = Logger.getLogger( DbUser.class ); - + public DbUser(int userId, String username, String password, String organization, String firstName, String lastName, String eMail, - String satelliteAddress) { - super(userId, username, password, organization, firstName, lastName, eMail, - satelliteAddress); + String satelliteAddress) + { + super( userId, username, password, organization, firstName, lastName, eMail, + satelliteAddress ); } /** * Query database for user with given login * * @param login - * (user@organization) + * (user@organization) * @return instance of DbUser for matching entry from DB, or null if not * found */ - public static DbUser forLogin(final String login) { - final String[] parts = login.split("@"); - if (parts.length != 2) + public static DbUser forLogin( final String login ) + { + final String[] parts = login.split( "@" ); + if ( parts.length != 2 ) return null; return MySQL .findUniqueOrNull( @@ -31,24 +35,27 @@ public class DbUser extends User { "SELECT user.userid, user.username, user.password, user.organization, user.firstname, user.lastname, user.email, satellite.address FROM user" + " LEFT JOIN satellite USING (organization)" + " WHERE user.username = ? AND user.organization = ? LIMIT 1", - parts[0], parts[1]); + parts[0], parts[1] ); } - public static boolean insertOrUpdate(User user) { - log.debug("Inserted user '" + user.username + "' into db."); - MySQL.update("INSERT INTO user (username, password, organization, firstname, lastname, email) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE password=VALUES(password), organization=VALUES(organization), firstname=VALUES(firstname), lastname=VALUES(lastname), email=VALUES(email)", - user.username, user.password, user.organization, user.firstName, user.lastName, user.eMail); + public static boolean insertOrUpdate( User user ) + { + log.debug( "Inserted user '" + user.username + "' into db." ); + MySQL.update( + "INSERT INTO user (username, password, organization, firstname, lastname, email) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE password=VALUES(password), organization=VALUES(organization), firstname=VALUES(firstname), lastname=VALUES(lastname), email=VALUES(email)", + user.username, user.password, user.organization, user.firstName, user.lastName, user.eMail ); return false; } - - public static int getUserIdByName(String username) { - DbUser user = MySQL + + public static int getUserIdByName( String username ) + { + DbUser user = MySQL .findUniqueOrNull( DbUser.class, "SELECT user.userid, user.username, user.password, user.organization, user.firstname, user.lastname, user.email, satellite.address FROM user" + " LEFT JOIN satellite USING (organization)" - + " WHERE user.username = ? LIMIT 1", username); - if (user != null) { + + " WHERE user.username = ? LIMIT 1", username ); + if ( user != null ) { return user.userId; } else { return 0; diff --git a/src/main/java/org/openslx/imagemaster/db/ImageProcessor.java b/src/main/java/org/openslx/imagemaster/db/ImageProcessor.java index 8c8bd8c..d0ac5c6 100644 --- a/src/main/java/org/openslx/imagemaster/db/ImageProcessor.java +++ b/src/main/java/org/openslx/imagemaster/db/ImageProcessor.java @@ -7,81 +7,83 @@ import org.apache.log4j.Logger; import org.openslx.imagemaster.Globals; import org.openslx.imagemaster.thrift.iface.ImageData; -public class ImageProcessor { +public class ImageProcessor +{ - private static Logger log = Logger.getLogger(ImageProcessor.class); + private static Logger log = Logger.getLogger( ImageProcessor.class ); private static HashMap<String, ImageData> images = new HashMap<>(); - /** * Processes an image after upload + * * @param username the user that uploaded the file * @param filename the name of the file that was uploaded (_no_ absolute path) * @return */ - public static boolean processImageAfterUpload(String username, String filename) { - if (!images.containsKey(username)) { + public static boolean processImageAfterUpload( String username, String filename ) + { + if ( !images.containsKey( username ) ) { return false; } - - log.info("Will now process '" + filename + "' from user '" + username - + "'"); + + log.info( "Will now process '" + filename + "' from user '" + username + + "'" ); // move image to right location - String oldFileName = Globals.properties.getProperty("ftp_base_dir") + "/" + username + "/" + filename; - String newFileName = Globals.properties.getProperty("image_dir") + "/" + images.get(username).uuid; - - File imageFile = new File(oldFileName); - - if (!imageFile.exists()) { + String oldFileName = Globals.getPropertyString( Globals.PropString.FTPBASEDIR ) + "/" + username + "/" + filename; + String newFileName = Globals.getPropertyString( Globals.PropString.IMAGEDIR ) + "/" + images.get( username ).uuid; + + File imageFile = new File( oldFileName ); + + if ( !imageFile.exists() ) { // image file does not exist return false; } - - imageFile.renameTo( new File(newFileName) ); - - log.info("Moved file from " + oldFileName + " to " + newFileName ); - - File tempUserDir = new File (Globals.properties.getProperty("ftp_base_dir") + "/" + username); + + imageFile.renameTo( new File( newFileName ) ); + + log.info( "Moved file from " + oldFileName + " to " + newFileName ); + + File tempUserDir = new File( Globals.getPropertyString( Globals.PropString.FTPBASEDIR ) + "/" + username ); tempUserDir.delete(); - + // update database - DbImage.update(images.get(username), newFileName); - log.info("Updated db: " + images.get(username).uuid); - - images.remove(username); + DbImage.update( images.get( username ), newFileName ); + log.info( "Updated db: " + images.get( username ).uuid ); + + images.remove( username ); return true; } /** - * Try to add imageData to db + * Try to add imageData to database. * * @param imageData - * the data for the image to add + * the data for the image to add * @return false if submit fails */ - public static boolean addImageDataToProcess(ImageData imageData, - String username) { - log.info("Adding image to process list: " + imageData.imageName + ", submitted by " + username); - - if (imageData.uuid.isEmpty() || imageData.imageName.isEmpty() + public static boolean addImageDataToProcess( ImageData imageData, String username ) + { + log.info( "Adding image to process list: " + imageData.imageName + ", submitted by " + username ); + + if ( imageData.uuid.isEmpty() || imageData.imageName.isEmpty() || imageData.imageOwner.isEmpty() || imageData.conentOperatingSystem.isEmpty() || imageData.imageShortDescription.isEmpty() - || imageData.imageLongDescription.isEmpty()) { + || imageData.imageLongDescription.isEmpty() ) { return false; } - + // TODO: check some regex? - - if (DbImage.exists(imageData)) { + + if ( DbImage.exists( imageData ) ) { return false; } - + // if everything went fine, add image to db - DbImage.insert(imageData); - + DbImage.insert( imageData ); + // and to processinglist - images.put(username, imageData); + images.put( username, imageData ); return true; } } diff --git a/src/main/java/org/openslx/imagemaster/db/LdapUser.java b/src/main/java/org/openslx/imagemaster/db/LdapUser.java index 1124696..08eb127 100644 --- a/src/main/java/org/openslx/imagemaster/db/LdapUser.java +++ b/src/main/java/org/openslx/imagemaster/db/LdapUser.java @@ -15,6 +15,8 @@ import org.apache.directory.ldap.client.api.LdapConnectionConfig; import org.apache.directory.ldap.client.api.LdapNetworkConnection; import org.apache.log4j.Logger; import org.openslx.imagemaster.Globals; +import org.openslx.imagemaster.Globals.PropBool; +import org.openslx.imagemaster.Globals.PropString; import org.openslx.imagemaster.session.User; import org.openslx.imagemaster.thrift.iface.AuthenticationError; import org.openslx.imagemaster.thrift.iface.AuthenticationException; @@ -26,21 +28,27 @@ import org.openslx.imagemaster.util.Sha512Crypt; * actually verify the cert, or we could just stop using ssl * altogether. */ -class MyTrustManager implements X509TrustManager { +class MyTrustManager implements X509TrustManager +{ @Override - public void checkClientTrusted(X509Certificate[] arg0, String arg1) - throws CertificateException {} + public void checkClientTrusted( X509Certificate[] arg0, String arg1 ) + throws CertificateException + { + } @Override - public void checkServerTrusted(X509Certificate[] arg0, String arg1) - throws CertificateException {} + public void checkServerTrusted( X509Certificate[] arg0, String arg1 ) + throws CertificateException + { + } @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; + public X509Certificate[] getAcceptedIssuers() + { + return new X509Certificate[ 0 ]; } - + } /** @@ -50,101 +58,104 @@ class MyTrustManager implements X509TrustManager { */ public class LdapUser extends User { + private static final Logger log = Logger.getLogger( LdapUser.class ); - - protected LdapUser(int userId, String username, String password, String organization, - String firstName, String lastName, String eMail, - String satelliteAddress) { - super(userId, username, password, organization, firstName, lastName, eMail, - satelliteAddress); + + protected LdapUser(int userId, String username, String password, String organization, String firstName, String lastName, String eMail, String satelliteAddress) + { + super( userId, username, password, organization, firstName, lastName, eMail, + satelliteAddress ); } - + /** * Query LDAP for user with given login - * @param login Login of user in the form "user@organization.com" + * + * @param login Login of user in the form "user@organization.com" * @return instance of LDAPUser for matching entry from LDAP, or null if not found */ - public static LdapUser forLogin( final String login, final String password ) throws AuthenticationException { + public static LdapUser forLogin( final String login, final String password ) throws AuthenticationException + { String username, organization, firstName, lastName, eMail, satelliteAddress; - - String[] temp = login.split("@"); - if (temp.length != 2) throw new AuthenticationException( AuthenticationError.GENERIC_ERROR, "Login must be in form user@organization.com"); + + String[] temp = login.split( "@" ); + if ( temp.length != 2 ) + throw new AuthenticationException( AuthenticationError.GENERIC_ERROR, "Login must be in form user@organization.com" ); username = temp[0]; - + LdapConnectionConfig ldapConfig = new LdapConnectionConfig(); - ldapConfig.setTrustManagers(new MyTrustManager()); - ldapConfig.setLdapPort(Integer.valueOf(Globals.properties.getProperty(Globals.ldapPort))); - ldapConfig.setLdapHost(Globals.properties.getProperty(Globals.ldapHost)); - ldapConfig.setUseSsl(Boolean.valueOf(Globals.properties.getProperty(Globals.ldapSsl))); - + ldapConfig.setTrustManagers( new MyTrustManager() ); + ldapConfig.setLdapPort( Globals.getPropertyInt( Globals.PropInt.LDAPPORT ) ); + ldapConfig.setLdapHost( Globals.getPropertyString( Globals.PropString.LDAPHOST ) ); + ldapConfig.setUseSsl( Globals.getPropertyBool( PropBool.LDAPSSL ) ); + LdapNetworkConnection connection = new LdapNetworkConnection( ldapConfig ); - + // bind connection try { if ( connection.connect() ) { - String name = Globals.properties.getProperty(Globals.ldapBindQuery).replace("%", username); - connection.bind(name, password); + String name = Globals.getPropertyString( PropString.LDAPBINDQUERY ).replace( "%", username ); + connection.bind( name, password ); } - } catch (LdapException e1) { + } catch ( LdapException e1 ) { log.warn( "Connection to LDAP failed: " + e1.getMessage() ); } - + if ( !connection.isConnected() ) { try { connection.unBind(); connection.close(); - } catch (LdapException | IOException e) { + } catch ( LdapException | IOException e ) { // Not doing anything here, as ldap already failed... } throw new AuthenticationException( AuthenticationError.GENERIC_ERROR, "Could not connect to LDAP server." ); } - + // test authorization if ( !connection.isAuthenticated() ) { try { connection.unBind(); connection.close(); - } catch (LdapException | IOException e) { + } catch ( LdapException | IOException e ) { // Failing disconnect... Can't do much about it, just go on } throw new AuthenticationException( AuthenticationError.INVALID_CREDENTIALS, "Could not authenticate to LDAP server. Invalid credentials?" ); } - + // make search query try { - EntryCursor cursor = connection.search(Globals.properties.getProperty(Globals.ldapSearchBaseDn), - Globals.properties.getProperty(Globals.ldapSearchFilter).replace("%", username), SearchScope.SUBTREE); + EntryCursor cursor = connection.search( Globals.getPropertyString( Globals.PropString.LDAPSEARCHBASEDN ), + Globals.getPropertyString( Globals.PropString.LDAPSEARCHFILTER ).replace( "%", username ), SearchScope.SUBTREE ); // only use the first result cursor.next(); Entry entry = cursor.get(); - username = entry.get("uid").getString(); + username = entry.get( "uid" ).getString(); organization = "Test Organization"; // will be filled with bwIDM LDAP server - firstName = entry.get("givenName").getString(); - lastName = entry.get("sn").getString(); - eMail = entry.get("rufPreferredMail").getString(); + firstName = entry.get( "givenName" ).getString(); + lastName = entry.get( "sn" ).getString(); + eMail = entry.get( "rufPreferredMail" ).getString(); // get the satellite address from db - DbSatellite dbSatellite = DbSatellite.fromOrganization(organization); - if (dbSatellite != null) { + DbSatellite dbSatellite = DbSatellite.fromOrganization( organization ); + if ( dbSatellite != null ) { satelliteAddress = dbSatellite.getAddress(); } else { // TODO: Organization is not known.. Handle this satelliteAddress = "addressNotKown"; } - } catch (LdapException | CursorException e1) { + } catch ( LdapException | CursorException e1 ) { return null; } finally { // close connection try { connection.unBind(); - } catch (LdapException e) { + } catch ( LdapException e ) { return null; } try { connection.close(); - } catch (IOException e) { + } catch ( IOException e ) { return null; } } - return new LdapUser(0, username, Sha512Crypt.Sha512_crypt(password, null, 0), organization, firstName, lastName, eMail, satelliteAddress); + return new LdapUser( 0, username, Sha512Crypt.Sha512_crypt( password, null, 0 ), organization, firstName, lastName, eMail, satelliteAddress ); } } diff --git a/src/main/java/org/openslx/imagemaster/db/MySQL.java b/src/main/java/org/openslx/imagemaster/db/MySQL.java index ebc44c7..121ef1b 100644 --- a/src/main/java/org/openslx/imagemaster/db/MySQL.java +++ b/src/main/java/org/openslx/imagemaster/db/MySQL.java @@ -25,7 +25,7 @@ class MySQL /** * Static initializer for setting up the database connection. - * This gets called implicitly as soon as the clas loader loads + * This gets called implicitly as soon as the class loader loads * the class. In most cases that happens when the class is being * accessed for the first time during run time. */ @@ -52,7 +52,7 @@ class MySQL final String dbname = properties.getProperty( "db" ); final String user = properties.getProperty( "user" ); final String password = properties.getProperty( "password" ); - + Util.notNullFatal( host, "host not set in mysql properties" ); Util.notNullFatal( dbname, "db not set in mysql properties" ); Util.notNullFatal( user, "user not set in mysql properties" ); @@ -77,7 +77,7 @@ class MySQL * Get a list of objects of the given class from the database. * The class needs a matching constructor for the query you pass in, i.e. number of * arguments has to be equal to number of columns returned by query. - * + * * @param clazz The class to instanciate for the result(s) * @param sql The sql query to run * @param args Any number of arguments to the query (using the '?' placeholder) @@ -92,7 +92,7 @@ class MySQL * Run a query on the database that will return at most one result. * If the query returns a row, it will be used to instanciate the given class. If * it doesn't return a row, null will be returned. - * + * * @param clazz The class to instanciate for the result (if any) * @param sql The sql query to run * @param args Any number of arguments to the query (using the '?' placeholder) @@ -102,16 +102,16 @@ class MySQL { return db.findUniqueOrNull( clazz, sql, args ); } - + /** * Run an update on the database, return number of rows affected. - * + * * @param sql The update/insert query to run * @param args Any number of arguments to the query (using the '?' placeholder) * @return Number of rows affected by query */ - protected static int update( String sql, Object... args) { + protected static int update( String sql, Object... args ) + { return db.update( sql, args ); } } - diff --git a/src/main/java/org/openslx/imagemaster/server/ApiServer.java b/src/main/java/org/openslx/imagemaster/server/ApiServer.java index df0aa3a..c88bd05 100644 --- a/src/main/java/org/openslx/imagemaster/server/ApiServer.java +++ b/src/main/java/org/openslx/imagemaster/server/ApiServer.java @@ -4,6 +4,7 @@ import java.io.File; import org.apache.log4j.Logger; import org.apache.thrift.TException; +import org.openslx.imagemaster.App; import org.openslx.imagemaster.Globals; import org.openslx.imagemaster.db.DbSatellite; import org.openslx.imagemaster.db.ImageProcessor; @@ -39,8 +40,9 @@ import org.openslx.imagemaster.thrift.iface.UserInfo; * This will be accessed from multiple threads, so use synchronization when * needed (or in doubt) */ -public class ApiServer { - private static Logger log = Logger.getLogger(ApiServer.class); +public class ApiServer +{ + private static Logger log = Logger.getLogger( ApiServer.class ); /** * Request for authentication @@ -50,17 +52,18 @@ public class ApiServer { * @return SessionData struct with session id/token iff login successful * @throws AuthenticationException if login not successful */ - public static SessionData authenticate(String login, String password) - throws AuthenticationException { - if (login == null || password == null) { + public static SessionData authenticate( String login, String password ) + throws AuthenticationException + { + if ( login == null || password == null ) { throw new AuthenticationException( AuthenticationError.INVALID_CREDENTIALS, - "Empty username or password!"); + "Empty username or password!" ); } - final User user = Authenticator.authenticate(login, password); + final User user = Authenticator.authenticate( login, password ); - final Session session = new Session(user); - return SessionManager.addSession(session); + final Session session = new Session( user ); + return SessionManager.addSession( session ); } /** @@ -70,121 +73,131 @@ public class ApiServer { * @return UserInfo struct for given token's user * @throws InvalidTokenException if no user matches the given token */ - public static UserInfo getUserFromToken(String token) - throws InvalidTokenException { - final Session session = SessionManager.getSession(token); - if (session == null) + public static UserInfo getUserFromToken( String token ) + throws InvalidTokenException + { + final Session session = SessionManager.getSession( token ); + if ( session == null ) throw new InvalidTokenException(); - return new UserInfo(session.getUserId(), session.getFirstName(), - session.getLastName(), session.getEMail()); + return new UserInfo( session.getUserId(), session.getFirstName(), + session.getLastName(), session.getEMail() ); } /** * Request ftp credentials to upload a new image to the masterserver. + * * @param imageDescription MetaData of the new image * @param serverSessionData the session data of the authenticated uni/hs server * @return the genereated ftp credentials * @throws AuthorizationException if the uni/hs server has no valid session * @throws TException */ - public static FtpCredentials submitImage(String serverSessionId, - ImageData imageDescription) throws AuthorizationException, - TException { - if (ServerSessionManager.getSession(serverSessionId) == null) { - throw new AuthorizationException(AuthorizationError.NOT_AUTHENTICATED, "No valid serverSessionData"); + public static FtpCredentials submitImage( String serverSessionId, + ImageData imageDescription ) throws AuthorizationException, + TException + { + if ( ServerSessionManager.getSession( serverSessionId ) == null ) { + throw new AuthorizationException( AuthorizationError.NOT_AUTHENTICATED, "No valid serverSessionData" ); } - + // create new user - FtpCredentials ftpCredentials = Globals.ftpServer.addUser(serverSessionId); - - if (ftpCredentials == null) { - log.error("Could not create ftp credentials"); + FtpCredentials ftpCredentials = App.ftpServer.addUser( serverSessionId ); + + if ( ftpCredentials == null ) { + log.error( "Could not create ftp credentials" ); return null; } - - if (!ImageProcessor.addImageDataToProcess(imageDescription, ftpCredentials.username)) { - Globals.ftpServer.removeUser(serverSessionId); - throw new TException("ImageData is not valid."); + + if ( !ImageProcessor.addImageDataToProcess( imageDescription, ftpCredentials.username ) ) { + App.ftpServer.removeUser( serverSessionId ); + throw new TException( "ImageData is not valid." ); } - + return ftpCredentials; } /** * Start the server authentication of a uni/hs satellite server. + * * @param organization the organization that the server belongs to * @return a random string that needs to be encrypted with the private - * key of the requesting satellite server + * key of the requesting satellite server * @throws ServerAuthenticationException when organization is invalid/unknown */ - public static String startServerAuthentication(String organization) - throws ServerAuthenticationException { - if (organization == null || organization == "") { - throw new ServerAuthenticationException(ServerAuthenticationError.INVALID_ORGANIZATION, "Empty organization"); + public static String startServerAuthentication( String organization ) + throws ServerAuthenticationException + { + if ( organization == null || organization == "" ) { + throw new ServerAuthenticationException( ServerAuthenticationError.INVALID_ORGANIZATION, "Empty organization" ); } - if (DbSatellite.fromOrganization(organization) == null) { - throw new ServerAuthenticationException(ServerAuthenticationError.INVALID_ORGANIZATION, "Unknown organization"); + if ( DbSatellite.fromOrganization( organization ) == null ) { + throw new ServerAuthenticationException( ServerAuthenticationError.INVALID_ORGANIZATION, "Unknown organization" ); } - return ServerAuthenticator.startServerAuthentication(organization); + return ServerAuthenticator.startServerAuthentication( organization ); } /** * Authenticate the uni/hs satellite server with the encrypted string. + * * @param organization the organization that the server belongs to * @param challengeResponse the encrypted string * @return session data iff the authentication was successful * @throws AuthenticationException * @throws TException */ - public static ServerSessionData serverAuthenticate(String organization, - String challengeResponse) throws AuthenticationException, - TException { - if (organization == null || challengeResponse == null) { - throw new ServerAuthenticationException(ServerAuthenticationError.INVALID_ORGANIZATION, "Empty organization or challengeResponse"); + public static ServerSessionData serverAuthenticate( String organization, + String challengeResponse ) throws AuthenticationException, + TException + { + if ( organization == null || challengeResponse == null ) { + throw new ServerAuthenticationException( ServerAuthenticationError.INVALID_ORGANIZATION, "Empty organization or challengeResponse" ); } - DbSatellite satellite = DbSatellite.fromOrganization(organization); - if (satellite == null) { - throw new ServerAuthenticationException(ServerAuthenticationError.INVALID_ORGANIZATION, "Unknown organization"); + DbSatellite satellite = DbSatellite.fromOrganization( organization ); + if ( satellite == null ) { + throw new ServerAuthenticationException( ServerAuthenticationError.INVALID_ORGANIZATION, "Unknown organization" ); } final ServerUser serverUser = ServerAuthenticator.serverAuthenticate( - organization, satellite.getAddress(), challengeResponse); - - final ServerSession session = new ServerSession(serverUser); - return ServerSessionManager.addSession(session); + organization, satellite.getAddress(), challengeResponse ); + + final ServerSession session = new ServerSession( serverUser ); + return ServerSessionManager.addSession( session ); } /** * Tell the masterserver that the image upload finished. + * * @param serverSessionId The session id of the hs/uni server * @param imageDescription the description of the uploaded image * @return if nothing went wrong * @throws AuthorizationException if no valid session exists */ - public static boolean finishedUpload(String serverSessionId, - ImageData imageDescription) throws AuthorizationException { + public static boolean finishedUpload( String serverSessionId, + ImageData imageDescription ) throws AuthorizationException + { // check if valid session exists - if (ServerSessionManager.getSession(serverSessionId) == null) { - throw new AuthorizationException(AuthorizationError.NOT_AUTHENTICATED, "No valid serverSessionData"); + if ( ServerSessionManager.getSession( serverSessionId ) == null ) { + throw new AuthorizationException( AuthorizationError.NOT_AUTHENTICATED, "No valid serverSessionData" ); } - + // process the image - String username = Globals.ftpServer.getCredentialsFromSessionId(serverSessionId).username; - - File userDirectory = new File(Globals.properties.getProperty(Globals.ftpBaseDir) + "/" + username); + String username = App.ftpServer.getCredentialsFromSessionId( serverSessionId ).username; + + File userDirectory = new File( Globals.getPropertyString( Globals.PropString.FTPBASEDIR ) + "/" + username ); File[] list = userDirectory.listFiles(); - - if (list.length != 1) return false; - - log.info(username + " is done with upload"); - + + if ( list.length != 1 ) + return false; + + log.info( username + " is done with upload" ); + // remove user that is not needed anymore - Globals.ftpServer.removeUser(username); - log.info("Removed user: " + username); - - ImageProcessor.processImageAfterUpload(username, list[0].getName()); - - Globals.ftpServer.removeUser(serverSessionId); - + App.ftpServer.removeUser( username ); + log.info( "Removed user: " + username ); + + ImageProcessor.processImageAfterUpload( username, list[0].getName() ); + + App.ftpServer.removeUser( serverSessionId ); + return true; } diff --git a/src/main/java/org/openslx/imagemaster/server/FtpCredentialsScheduler.java b/src/main/java/org/openslx/imagemaster/server/FtpCredentialsScheduler.java new file mode 100644 index 0000000..ba88f33 --- /dev/null +++ b/src/main/java/org/openslx/imagemaster/server/FtpCredentialsScheduler.java @@ -0,0 +1,63 @@ +package org.openslx.imagemaster.server; + +import java.io.File; +import java.util.Date; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; + +import org.apache.log4j.Logger; +import org.openslx.imagemaster.App; +import org.openslx.imagemaster.Globals; +import org.openslx.imagemaster.thrift.iface.FtpCredentials; +import org.openslx.imagemaster.util.Util; + +public class FtpCredentialsScheduler extends TimerTask +{ + private static Logger log = Logger.getLogger( FtpCredentialsScheduler.class ); + + public static final long timeout = Long.valueOf( Globals.getPropertyInt( Globals.PropInt.FTPTIMEOUT ) ) * 60L * 1000L; // timeout in ms + + @Override + public void run() + { + // check all folders + for ( Map.Entry<String, FtpCredentials> entry : App.ftpServer.users.entrySet() ) { + String sessionId = entry.getKey(); + String username = entry.getValue().username; + File dir = new File( Globals.getPropertyString( Globals.PropString.FTPBASEDIR ) + "/" + username ); + if ( !dir.exists() ) + continue; + File[] list = dir.listFiles(); + if ( list.length == 1 ) { + if ( ( new Date().getTime() - list[0].lastModified() ) >= timeout ) { + log.info( username + "'s files are too old. Deleting him and his folder." ); + Util.deleteFolder( dir ); + App.ftpServer.removeUser( sessionId ); + } + } else if ( list.length > 1 ) { + log.info( username + " uploaded too many files. Deleting his account and his folder." ); + Util.deleteFolder( dir ); + App.ftpServer.removeUser( sessionId ); + } else { + // check the creation time of the user + if ( ( new Date().getTime() - App.ftpServer.timeouts.get( username ).getTime() ) >= timeout ) { + // remove user and his folder + Util.deleteFolder( dir ); + App.ftpServer.removeUser( sessionId ); + log.info( username + " did nothing for too long. Deleting him and his folder" ); + } + } + } + //TODO: remove image from process list + } + + public static void startScheduling() + { + Timer timer = new Timer(); + + // start timer now and fire every 60 seconds + timer.schedule( new FtpCredentialsScheduler(), 0, 60000 ); + } + +} diff --git a/src/main/java/org/openslx/imagemaster/server/MasterFtpServer.java b/src/main/java/org/openslx/imagemaster/server/MasterFtpServer.java index d1ec14f..de0d758 100644 --- a/src/main/java/org/openslx/imagemaster/server/MasterFtpServer.java +++ b/src/main/java/org/openslx/imagemaster/server/MasterFtpServer.java @@ -13,6 +13,7 @@ import org.apache.ftpserver.ftplet.FtpException; import org.apache.ftpserver.ftplet.Ftplet; import org.apache.ftpserver.ftplet.UserManager; import org.apache.ftpserver.listener.ListenerFactory; +import org.apache.ftpserver.ssl.SslConfigurationFactory; import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory; import org.apache.ftpserver.usermanager.SaltedPasswordEncryptor; import org.apache.ftpserver.usermanager.impl.BaseUser; @@ -22,7 +23,8 @@ import org.openslx.imagemaster.Globals; import org.openslx.imagemaster.thrift.iface.FtpCredentials; import org.openslx.imagemaster.util.RandomString; -public class MasterFtpServer implements Runnable { +public class MasterFtpServer implements Runnable +{ private static Logger log = Logger.getLogger( MasterFtpServer.class ); private FtpServer server; private UserManager userManager; @@ -30,96 +32,111 @@ public class MasterFtpServer implements Runnable { public final HashMap<String, FtpCredentials> users = new HashMap<>(); // key: ftpUsername, value: createTime public final HashMap<String, Date> timeouts = new HashMap<>(); - - public MasterFtpServer(int port, String adminUsername, String adminPassword, String ftproot) { + private boolean ini = false; + + public void init( int port ) + { + if ( ini ) + return; + FtpServerFactory serverFactory = new FtpServerFactory(); ListenerFactory factory = new ListenerFactory(); + + // config ssl + SslConfigurationFactory sslConfigFactory = new SslConfigurationFactory(); + sslConfigFactory.setKeystoreFile( new File( "./keyfiles/ftp.jks" ) ); + sslConfigFactory.setKeyAlias( "ftp" ); + sslConfigFactory.setKeystorePassword( "password" ); + // set the port of the listener - factory.setPort(port); - + factory.setPort( port ); + factory.setSslConfiguration( sslConfigFactory.createSslConfiguration() ); + factory.setImplicitSsl( true ); + // replace the default listener - serverFactory.addListener("default", factory.createListener()); - + serverFactory.addListener( "default", factory.createListener() ); + // create user manager - PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory(); - userManagerFactory.setFile(new File("src/main/properties/ftp.properties")); - userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor()); - userManager = userManagerFactory.createUserManager(); - - // create new admin user - //addUser(adminUsername, adminPassword, ftproot, true); - serverFactory.setUserManager(userManager); - + PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory(); + userManagerFactory.setFile( new File( "src/main/properties/ftp.properties" ) ); + userManagerFactory.setPasswordEncryptor( new SaltedPasswordEncryptor() ); + userManager = userManagerFactory.createUserManager(); + serverFactory.setUserManager( userManager ); + // add the Ftplet HashMap<String, Ftplet> map = new HashMap<String, Ftplet>(); - map.put("Ftplet1", new MasterFtplet()); - serverFactory.setFtplets(map); - + map.put( "Ftplet1", new MasterFtplet() ); + serverFactory.setFtplets( map ); + // start the server server = serverFactory.createServer(); + ini = true; } - public FtpCredentials addUser(final String serverSessionId) { - // TODO: enable SSL - + public FtpCredentials addUser( final String serverSessionId ) + { FtpCredentials ftpCredentials = null; - - String generatedUser = RandomString.generate(10, false); - String generatedPass = RandomString.generate(16, true); - - String dir = Globals.properties.getProperty(Globals.ftpBaseDir) + "/" + + String generatedUser = RandomString.generate( 10, false ); + String generatedPass = RandomString.generate( 16, true ); + + String dir = Globals.getPropertyString( Globals.PropString.FTPBASEDIR ) + "/" + generatedUser + "/"; - - if (!new File(dir).mkdir()) { + + if ( !new File( dir ).mkdir() ) { return ftpCredentials; } - BaseUser user = new BaseUser(); - user.setName(generatedUser); - user.setPassword(generatedPass); - user.setHomeDirectory(dir); - - List<Authority> authorities = new ArrayList<Authority>(); - authorities.add(new WritePermission()); - user.setAuthorities(authorities); - - try { - userManager.save(user); - ftpCredentials = new FtpCredentials(generatedUser, generatedPass); - users.put(serverSessionId, ftpCredentials); - timeouts.put(ftpCredentials.username, new Date()); - } catch (FtpException e) { - } - - log.info("Generated user/pass: " + generatedUser + "\t" - + generatedPass + "\n with home dir: " + dir); - - return ftpCredentials; + BaseUser user = new BaseUser(); + user.setName( generatedUser ); + user.setPassword( generatedPass ); + user.setHomeDirectory( dir ); + + List<Authority> authorities = new ArrayList<Authority>(); + authorities.add( new WritePermission() ); + user.setAuthorities( authorities ); + + try { + userManager.save( user ); + ftpCredentials = new FtpCredentials( generatedUser, generatedPass ); + users.put( serverSessionId, ftpCredentials ); + timeouts.put( ftpCredentials.username, new Date() ); + } catch ( FtpException e ) { + } + + log.info( "Generated user/pass: " + generatedUser + "\t" + + generatedPass + "\n with home dir: " + dir ); + + return ftpCredentials; } - - public boolean removeUser(final String serverSessionId) { - if (!users.containsKey(serverSessionId)) return false; - + + public boolean removeUser( final String serverSessionId ) + { + if ( !users.containsKey( serverSessionId ) ) + return false; + try { - userManager.delete(users.get(serverSessionId).username); + userManager.delete( users.get( serverSessionId ).username ); // remove user from both maps - timeouts.remove(users.remove(serverSessionId).username); + timeouts.remove( users.remove( serverSessionId ).username ); return true; - } catch (FtpException e) { + } catch ( FtpException e ) { return false; } } - - public FtpCredentials getCredentialsFromSessionId(String serverSessionId) { - return users.get(serverSessionId); + + public FtpCredentials getCredentialsFromSessionId( String serverSessionId ) + { + return users.get( serverSessionId ); } @Override - public void run() { + public void run() + { try { log.info( "Starting FTP Sever" ); server.start(); - } catch (FtpException e1) { + } catch ( FtpException e1 ) { e1.printStackTrace(); } } diff --git a/src/main/java/org/openslx/imagemaster/server/MasterFtplet.java b/src/main/java/org/openslx/imagemaster/server/MasterFtplet.java index 479729d..a8c1cbe 100644 --- a/src/main/java/org/openslx/imagemaster/server/MasterFtplet.java +++ b/src/main/java/org/openslx/imagemaster/server/MasterFtplet.java @@ -9,63 +9,54 @@ import org.apache.ftpserver.ftplet.FtpSession; import org.apache.ftpserver.ftplet.Ftplet; import org.apache.ftpserver.ftplet.FtpletContext; import org.apache.ftpserver.ftplet.FtpletResult; -import org.apache.ftpserver.ftplet.UserManager; import org.apache.log4j.Logger; -import org.openslx.imagemaster.db.ImageProcessor; -public class MasterFtplet implements Ftplet { - private static Logger log = Logger.getLogger(Ftplet.class); - private UserManager userManager; +public class MasterFtplet implements Ftplet +{ + private static Logger log = Logger.getLogger( Ftplet.class ); @Override - public void init(FtpletContext ftpletContext) throws FtpException { - userManager = ftpletContext.getUserManager(); + public void init( FtpletContext ftpletContext ) throws FtpException + { + // not used } @Override - public void destroy() { + public void destroy() + { // not used } @Override - public FtpletResult beforeCommand(FtpSession session, FtpRequest request) - throws FtpException, IOException { - if (session.getUser() != null) { - log.info(session.getUser().getName() + " issued command: " + request.getRequestLine()); + public FtpletResult beforeCommand( FtpSession session, FtpRequest request ) + throws FtpException, IOException + { + if ( session.getUser() != null ) { + log.info( session.getUser().getName() + " issued command: " + request.getRequestLine() ); } return null; } @Override - public FtpletResult afterCommand(FtpSession session, FtpRequest request, - FtpReply reply) throws FtpException, IOException { - if (session.getUser() != null) { - String username = session.getUser().getName(); - String command = request.getRequestLine(); - log.info(username + " is done with command: " + command); - if (request.getCommand().equals("STOR")) { - try { - userManager.delete(username); - } catch (FtpException e) { - } finally { - log.info("Stored file and deleted user: '" + username + "'"); - ImageProcessor.processImageAfterUpload(username, command.split(" ")[1]); - } - } - } + public FtpletResult afterCommand( FtpSession session, FtpRequest request, + FtpReply reply ) throws FtpException, IOException + { + // not used return null; } @Override - public FtpletResult onConnect(FtpSession session) throws FtpException, - IOException { + public FtpletResult onConnect( FtpSession session ) throws FtpException, + IOException + { // not used return null; } @Override - public FtpletResult onDisconnect(FtpSession session) throws FtpException, - IOException { + public FtpletResult onDisconnect( FtpSession session ) throws FtpException, + IOException + { // not used return null; } diff --git a/src/main/java/org/openslx/imagemaster/serversession/ServerAuthenticator.java b/src/main/java/org/openslx/imagemaster/serversession/ServerAuthenticator.java index d57eb36..726b062 100644 --- a/src/main/java/org/openslx/imagemaster/serversession/ServerAuthenticator.java +++ b/src/main/java/org/openslx/imagemaster/serversession/ServerAuthenticator.java @@ -7,8 +7,9 @@ import org.apache.thrift.TException; import org.openslx.imagemaster.thrift.iface.AuthenticationException; import org.openslx.imagemaster.util.RandomString; -public class ServerAuthenticator { - private static Logger log = Logger.getLogger(ServerAuthenticator.class); +public class ServerAuthenticator +{ + private static Logger log = Logger.getLogger( ServerAuthenticator.class ); // map of currently authenticating servers private static HashMap<String, String> authenticatingServers = new HashMap<String, String>(); @@ -16,16 +17,17 @@ public class ServerAuthenticator { * Start the server authentification. * * @param organization - * the organization of the server + * the organization of the server * @return encrypted random string */ - public static String startServerAuthentication(String organization) { - String secret = RandomString.generate(100, false); - synchronized (authenticatingServers) { - authenticatingServers.put(organization, secret); - log.info("Server of organinzation '" + organization + public static String startServerAuthentication( String organization ) + { + String secret = RandomString.generate( 100, false ); + synchronized ( authenticatingServers ) { + authenticatingServers.put( organization, secret ); + log.info( "Server of organinzation '" + organization + "' starts to authenticate. And got string: '" + secret - + "'"); + + "'" ); } return secret; } @@ -40,23 +42,24 @@ public class ServerAuthenticator { * @throws AuthenticationException * @throws TException */ - public static ServerUser serverAuthenticate(String organization, - String address, String challengeResponse) - throws AuthenticationException, TException { + public static ServerUser serverAuthenticate( String organization, + String address, String challengeResponse ) + throws AuthenticationException, TException + { /* * TODO: Decrypt the given challengeResponse and check whether it was * right or not. Authenticate server if so. */ - if (!challengeResponse.equals(authenticatingServers.get(organization))) { + if ( !challengeResponse.equals( authenticatingServers.get( organization ) ) ) { throw new AuthenticationException(); } - - log.info("Server of organinzation '" + organization + + log.info( "Server of organinzation '" + organization + " authenticated. With response: '" + challengeResponse - + "'"); + + "'" ); - authenticatingServers.remove(organization); + authenticatingServers.remove( organization ); - return new ServerUser(organization, address); + return new ServerUser( organization, address ); } } diff --git a/src/main/java/org/openslx/imagemaster/serversession/ServerSession.java b/src/main/java/org/openslx/imagemaster/serversession/ServerSession.java index 818439c..355fc0b 100644 --- a/src/main/java/org/openslx/imagemaster/serversession/ServerSession.java +++ b/src/main/java/org/openslx/imagemaster/serversession/ServerSession.java @@ -1,13 +1,15 @@ package org.openslx.imagemaster.serversession; +import org.openslx.imagemaster.Globals; +import org.openslx.imagemaster.Globals.PropInt; + /** * Holds the session id of the server and manages the timeout. - * @author nils - * + * */ -public class ServerSession { - - private static final long TIMEOUT = 600L * 1000L; // TODO: config +public class ServerSession +{ + private static final long TIMEOUT = Long.valueOf( Globals.getPropertyInt( PropInt.SESSIONTIMEOUTSERVER ) ) * 1000L; private long timeOut = 0; private final ServerUser serverUser; @@ -29,12 +31,14 @@ public class ServerSession { { return System.currentTimeMillis() > this.timeOut; } - - public String getOrganization() { + + public String getOrganization() + { return serverUser.organization; } - - public String getAddress() { + + public String getAddress() + { return serverUser.address; } } diff --git a/src/main/java/org/openslx/imagemaster/serversession/ServerSessionManager.java b/src/main/java/org/openslx/imagemaster/serversession/ServerSessionManager.java index e88c1f9..cd0cfc9 100644 --- a/src/main/java/org/openslx/imagemaster/serversession/ServerSessionManager.java +++ b/src/main/java/org/openslx/imagemaster/serversession/ServerSessionManager.java @@ -12,11 +12,12 @@ import org.openslx.imagemaster.util.Hash; /** * Manages all server sessions and kicks timeouted sessions. + * * @author nils - * + * */ -public class ServerSessionManager { - +public class ServerSessionManager +{ private static Logger log = Logger.getLogger( SessionManager.class ); // Map of currently known sessions @@ -47,6 +48,7 @@ public class ServerSessionManager { static { gcThread = new Thread( new Runnable() { + @Override public void run() { diff --git a/src/main/java/org/openslx/imagemaster/serversession/ServerUser.java b/src/main/java/org/openslx/imagemaster/serversession/ServerUser.java index 48815a8..d3a4d62 100644 --- a/src/main/java/org/openslx/imagemaster/serversession/ServerUser.java +++ b/src/main/java/org/openslx/imagemaster/serversession/ServerUser.java @@ -1,9 +1,11 @@ package org.openslx.imagemaster.serversession; -public class ServerUser { +public class ServerUser +{ public final String organization, address; - public ServerUser(String organization, String address) { + public ServerUser(String organization, String address) + { this.organization = organization; this.address = address; } diff --git a/src/main/java/org/openslx/imagemaster/session/Authenticator.java b/src/main/java/org/openslx/imagemaster/session/Authenticator.java index 3f86fad..aaaa7d7 100644 --- a/src/main/java/org/openslx/imagemaster/session/Authenticator.java +++ b/src/main/java/org/openslx/imagemaster/session/Authenticator.java @@ -6,13 +6,13 @@ import org.openslx.imagemaster.db.LdapUser; import org.openslx.imagemaster.thrift.iface.AuthenticationError; import org.openslx.imagemaster.thrift.iface.AuthenticationException; - public class Authenticator { private static Logger log = Logger.getLogger( Authenticator.class ); /** * Authenticate the user against whatever backend + * * @param username * @param password * @return @@ -20,23 +20,23 @@ public class Authenticator */ public static User authenticate( String username, String password ) throws AuthenticationException { -// DbUser user = DbUser.forLogin( username ); -// if ( user == null || !Sha512Crypt.verifyPassword( password, user.password ) ) { -// log.debug( "Login failed: " + username ); -// throw new AuthenticationException( AuthenticationError.INVALID_CREDENTIALS, "Invalid username or password!" ); -// } -// log.debug( "Login successful: " + username ); - + // DbUser user = DbUser.forLogin( username ); + // if ( user == null || !Sha512Crypt.verifyPassword( password, user.password ) ) { + // log.debug( "Login failed: " + username ); + // throw new AuthenticationException( AuthenticationError.INVALID_CREDENTIALS, "Invalid username or password!" ); + // } + // log.debug( "Login successful: " + username ); + LdapUser user = LdapUser.forLogin( username, password ); // throws exception if credentials are invalid - if (user == null) { - log.debug( "Login failed: " + username); + if ( user == null ) { + log.debug( "Login failed: " + username ); throw new AuthenticationException( AuthenticationError.INVALID_CREDENTIALS, "Invalid username or password!" ); } log.debug( "Login succesful: " + username ); - + // if successfull: update/insert into db - DbUser.insertOrUpdate(user); - + DbUser.insertOrUpdate( user ); + return user; } // diff --git a/src/main/java/org/openslx/imagemaster/session/Session.java b/src/main/java/org/openslx/imagemaster/session/Session.java index 8dc7f2b..39861a1 100644 --- a/src/main/java/org/openslx/imagemaster/session/Session.java +++ b/src/main/java/org/openslx/imagemaster/session/Session.java @@ -1,5 +1,8 @@ package org.openslx.imagemaster.session; +import org.openslx.imagemaster.Globals; +import org.openslx.imagemaster.Globals.PropInt; + /** * Simple representation of a user session. Contains user-related data and * information on whether the session is still valid. @@ -7,7 +10,7 @@ package org.openslx.imagemaster.session; */ public class Session { - private static final long TIMEOUT = 600L * 1000L; // TODO: config + private static final long TIMEOUT = Long.valueOf( Globals.getPropertyInt( PropInt.SESSIONTIMEOUTUSER ) ) * 1000L; private long timeOut = 0; private final User user; diff --git a/src/main/java/org/openslx/imagemaster/session/SessionManager.java b/src/main/java/org/openslx/imagemaster/session/SessionManager.java index cc68d0b..7891904 100644 --- a/src/main/java/org/openslx/imagemaster/session/SessionManager.java +++ b/src/main/java/org/openslx/imagemaster/session/SessionManager.java @@ -46,6 +46,7 @@ public class SessionManager static { gcThread = new Thread( new Runnable() { + @Override public void run() { diff --git a/src/main/java/org/openslx/imagemaster/session/User.java b/src/main/java/org/openslx/imagemaster/session/User.java index 7ff9a24..82ba8ca 100644 --- a/src/main/java/org/openslx/imagemaster/session/User.java +++ b/src/main/java/org/openslx/imagemaster/session/User.java @@ -7,7 +7,6 @@ package org.openslx.imagemaster.session; */ public abstract class User { - public final String username, organization; public final String password; public final String firstName, lastName; diff --git a/src/main/java/org/openslx/imagemaster/thrift/server/ImageServerHandler.java b/src/main/java/org/openslx/imagemaster/thrift/server/ImageServerHandler.java index 899af1a..16496a2 100644 --- a/src/main/java/org/openslx/imagemaster/thrift/server/ImageServerHandler.java +++ b/src/main/java/org/openslx/imagemaster/thrift/server/ImageServerHandler.java @@ -16,12 +16,12 @@ import org.openslx.imagemaster.thrift.iface.UserInfo; public class ImageServerHandler implements ImageServer.Iface { private static Logger log = Logger.getLogger( ImageServerHandler.class ); - + @Override public boolean ping() throws TException { - log.debug("Ping..."); - // TODO: Return false if service unavailable but running + log.debug( "Ping..." ); + // Return false if service unavailable but running return true; } @@ -40,29 +40,33 @@ public class ImageServerHandler implements ImageServer.Iface } @Override - public String startServerAuthentication(String organization) - throws TException { - return ApiServer.startServerAuthentication(organization); + public String startServerAuthentication( String organization ) + throws TException + { + return ApiServer.startServerAuthentication( organization ); } @Override - public ServerSessionData serverAuthenticate(String organization, - String challengeResponse) throws AuthenticationException, - TException { - return ApiServer.serverAuthenticate(organization, challengeResponse); + public ServerSessionData serverAuthenticate( String organization, + String challengeResponse ) throws AuthenticationException, + TException + { + return ApiServer.serverAuthenticate( organization, challengeResponse ); } @Override - public FtpCredentials submitImage(String serverSessionId, - ImageData imageDescription) throws AuthorizationException, - TException { - return ApiServer.submitImage(serverSessionId, imageDescription); + public FtpCredentials submitImage( String serverSessionId, + ImageData imageDescription ) throws AuthorizationException, + TException + { + return ApiServer.submitImage( serverSessionId, imageDescription ); } @Override - public boolean finshedUpload(String serverSessionId, - ImageData imageDescription) throws AuthorizationException { - return ApiServer.finishedUpload(serverSessionId, imageDescription); + public boolean finshedUpload( String serverSessionId, + ImageData imageDescription ) throws AuthorizationException + { + return ApiServer.finishedUpload( serverSessionId, imageDescription ); } } diff --git a/src/main/java/org/openslx/imagemaster/thrift/server/TBinaryProtocolSafe.java b/src/main/java/org/openslx/imagemaster/thrift/server/TBinaryProtocolSafe.java index 614be22..08654d6 100644 --- a/src/main/java/org/openslx/imagemaster/thrift/server/TBinaryProtocolSafe.java +++ b/src/main/java/org/openslx/imagemaster/thrift/server/TBinaryProtocolSafe.java @@ -18,12 +18,13 @@ import org.apache.thrift.transport.TTransport; */ public class TBinaryProtocolSafe extends TBinaryProtocol { - /** * Factory */ + @SuppressWarnings( "serial" ) public static class Factory implements TProtocolFactory { + protected boolean strictRead_ = false; protected boolean strictWrite_ = true; @@ -75,7 +76,7 @@ public class TBinaryProtocolSafe extends TBinaryProtocol if ( version != VERSION_1 ) { throw new TProtocolException( TProtocolException.BAD_VERSION, "Bad version in readMessageBegin" ); } - return new TMessage( readString(), (byte)( size & 0x000000ff ), readI32() ); + return new TMessage( readString(), (byte) ( size & 0x000000ff ), readI32() ); } else { if ( strictRead_ ) { throw new TProtocolException( TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?" ); @@ -113,7 +114,7 @@ public class TBinaryProtocolSafe extends TBinaryProtocol return bb; } - byte[] buf = new byte[size]; + byte[] buf = new byte[ size ]; trans_.readAll( buf, 0, size ); return ByteBuffer.wrap( buf ); } diff --git a/src/main/java/org/openslx/imagemaster/util/Hash.java b/src/main/java/org/openslx/imagemaster/util/Hash.java index 24eb595..8db6a5f 100644 --- a/src/main/java/org/openslx/imagemaster/util/Hash.java +++ b/src/main/java/org/openslx/imagemaster/util/Hash.java @@ -10,6 +10,7 @@ public class Hash * Cache of md5 digesters */ private static final ThreadLocal<MessageDigest> md5hash = new ThreadLocal<MessageDigest>() { + @Override public MessageDigest initialValue() { @@ -17,7 +18,7 @@ public class Hash return MessageDigest.getInstance( "MD5" ); } catch ( NoSuchAlgorithmException e ) { e.printStackTrace(); - System.exit(1); + System.exit( 1 ); return null; } } @@ -26,6 +27,7 @@ public class Hash * Cache of sha256 digesters */ private static final ThreadLocal<MessageDigest> sha256hash = new ThreadLocal<MessageDigest>() { + @Override public MessageDigest initialValue() { @@ -33,7 +35,7 @@ public class Hash return MessageDigest.getInstance( "SHA-256" ); } catch ( NoSuchAlgorithmException e ) { e.printStackTrace(); - System.exit(1); + System.exit( 1 ); return null; } } @@ -48,7 +50,7 @@ public class Hash private static final Charset UTF8 = Charset.forName( "UTF-8" ); // MD5 - + /** * Compute md5 hash of given binary data. * @@ -59,7 +61,7 @@ public class Hash { return toHexString( md5hash.get().digest( bytes ) ); } - + /** * Compute md5 hash of the given string. * The string will be converted to utf-8 before computation. @@ -69,11 +71,11 @@ public class Hash */ public static String md5( final String text ) { - return md5( text.getBytes( UTF8 )); + return md5( text.getBytes( UTF8 ) ); } - + // SHA-256 - + /** * Compute sha256 hash of given binary data. * @@ -94,20 +96,20 @@ public class Hash */ public static String sha256( final String text ) { - return sha256( text.getBytes( UTF8 )); + return sha256( text.getBytes( UTF8 ) ); } - + // Helper - + /** * Convert given binary data to hex. * * @param bytes binary data in a byte array - * @return upper case hex representation of bytes + * @return upper case hex representation of bytes */ private static String toHexString( final byte[] bytes ) { - final char[] hexChars = new char[bytes.length * 2]; + final char[] hexChars = new char[ bytes.length * 2 ]; for ( int j = 0; j < bytes.length; ++j ) { final int v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_CHARS[v >>> 4]; diff --git a/src/main/java/org/openslx/imagemaster/util/RandomString.java b/src/main/java/org/openslx/imagemaster/util/RandomString.java index a0e9419..fc4f9d3 100644 --- a/src/main/java/org/openslx/imagemaster/util/RandomString.java +++ b/src/main/java/org/openslx/imagemaster/util/RandomString.java @@ -4,25 +4,27 @@ import java.security.SecureRandom; /** * Generate secure random strings - * @author nils - * + * */ -public class RandomString { - private static final String lettersSpecial="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890+-$%&/()=?@"; - private static final String letters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; +public class RandomString +{ + private static final String lettersSpecial = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890+-$%&/()=?@"; + private static final String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; private static final SecureRandom random = new SecureRandom(); - + /** * Generate a random string. + * * @param length the length of the string * @param specialChars whether to use special charachters or not * @return the generated string */ - public static String generate(int length, boolean specialChars) { - String used = (specialChars)? lettersSpecial : letters; + public static String generate( int length, boolean specialChars ) + { + String used = ( specialChars ) ? lettersSpecial : letters; String result = ""; - for (int i = 0; i < length; i++) { - int index = (int)(random.nextDouble()*used.length()); + for ( int i = 0; i < length; i++ ) { + int index = (int) ( random.nextDouble() * used.length() ); result += used.substring( index, index + 1 ); } return result; diff --git a/src/main/java/org/openslx/imagemaster/util/Util.java b/src/main/java/org/openslx/imagemaster/util/Util.java index 9e0f708..0df4212 100644 --- a/src/main/java/org/openslx/imagemaster/util/Util.java +++ b/src/main/java/org/openslx/imagemaster/util/Util.java @@ -7,6 +7,7 @@ import org.apache.log4j.Logger; public class Util { + private static Logger log = Logger.getLogger( Util.class ); /** @@ -31,12 +32,12 @@ public class Util System.exit( 2 ); } } - + /** * Static {@link Random} instance. */ private static final Random random = new Random(); - + /** * Return a random integer in the range of 0 (inclusive) and * n (exclusive). Uses the internal static instance of {@link Random}, @@ -49,23 +50,25 @@ public class Util { return random.nextInt( n ); } - + /** * Remove a folder and all contents + * * @param folder */ - public static void deleteFolder(File folder) { - File[] files = folder.listFiles(); - if (files!=null) { - for (File f: files) { - if (f.isDirectory()) { - deleteFolder(f); - } else { - f.delete(); - } - } - } - folder.delete(); + public static void deleteFolder( File folder ) + { + File[] files = folder.listFiles(); + if ( files != null ) { + for ( File f : files ) { + if ( f.isDirectory() ) { + deleteFolder( f ); + } else { + f.delete(); + } + } + } + folder.delete(); } } diff --git a/src/test/java/org/openslx/imagemaster/AppTest.java b/src/test/java/org/openslx/imagemaster/AppTest.java index 89e72c1..291206b 100644 --- a/src/test/java/org/openslx/imagemaster/AppTest.java +++ b/src/test/java/org/openslx/imagemaster/AppTest.java @@ -31,83 +31,87 @@ import org.openslx.imagemaster.util.Sha512Crypt; /** * Unit test for simple App. */ -public class AppTest - extends TestCase +public class AppTest + extends TestCase { - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } - - /** - * Test the authentication - * @throws TException - */ - public void testAuthentication() throws TException { - TTransport transport = new TSocket("localhost", 9090); + + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest(String testName) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } + + /** + * Test the authentication + * + * @throws TException + */ + public void testAuthentication() throws TException + { + TTransport transport = new TSocket( "localhost", 9090 ); transport.open(); - - TProtocol protocol = new TBinaryProtocol(transport); - Client client = new Client(protocol); - - assertTrue("Could not ping server", client.ping()); - - SessionData sessionData = client.authenticate("ns202", "xxxxxxxxxxxx"); - UserInfo userInfo = client.getUserFromToken(sessionData.getAuthToken()); - System.out.println("User info: " + userInfo); - System.out.println("Server address from MySQL: " + sessionData.serverAddress); - } - - /** - * Test the server authentication and FTP Upload. - * @throws TException - * @throws IOException - * @throws SocketException - */ - public void testServerAuth() throws TException, SocketException, IOException { - TTransport transport = new TSocket("localhost", 9090); + + TProtocol protocol = new TBinaryProtocol( transport ); + Client client = new Client( protocol ); + + assertTrue( "Could not ping server", client.ping() ); + + SessionData sessionData = client.authenticate( "ns202", "xxxxxxxxxxxx" ); + UserInfo userInfo = client.getUserFromToken( sessionData.getAuthToken() ); + System.out.println( "User info: " + userInfo ); + System.out.println( "Server address from MySQL: " + sessionData.serverAddress ); + } + + /** + * Test the server authentication and FTP Upload. + * + * @throws TException + * @throws IOException + * @throws SocketException + */ + public void testServerAuth() throws TException, SocketException, IOException + { + TTransport transport = new TSocket( "localhost", 9090 ); transport.open(); - - TProtocol protocol = new TBinaryProtocol(transport); - Client client = new Client(protocol); - - assertTrue("Could not ping server", client.ping()); - - String stringToEncrypt = client.startServerAuthentication("Test Organization"); - System.out.println("Authentication started. Got string: " + stringToEncrypt); - + + TProtocol protocol = new TBinaryProtocol( transport ); + Client client = new Client( protocol ); + + assertTrue( "Could not ping server", client.ping() ); + + String stringToEncrypt = client.startServerAuthentication( "Test Organization" ); + System.out.println( "Authentication started. Got string: " + stringToEncrypt ); + String response = stringToEncrypt; - - ServerSessionData data = client.serverAuthenticate("Test Organization", response); - System.out.println("Authenticated and got sid: '" + data.getSessionId() + "'"); - - + + ServerSessionData data = client.serverAuthenticate( "Test Organization", response ); + System.out.println( "Authenticated and got sid: '" + data.getSessionId() + "'" ); + // Create ImageData int version = 1; String imageName = "maschine.vmkd"; UUID uuid = UUID.randomUUID(); - int imageCreateTime = (int) new Date().getTime(); + int imageCreateTime = (int)new Date().getTime(); int imageUpdateTime = imageCreateTime; String imageOwner = "ns202"; String contentOperatingSystem = "win7"; @@ -115,58 +119,59 @@ public class AppTest boolean statusIsDeleted = false; String imageShortDescrption = "EIN SUPER TOLLES IMAGE!"; String imageLongDescription = "Lorem ipsum dolor sit amet."; - - ImageData imageData = new ImageData(uuid.toString(), version, imageName, + + ImageData imageData = new ImageData( uuid.toString(), version, imageName, imageCreateTime, imageUpdateTime, imageOwner, contentOperatingSystem, - statusIsValid, statusIsDeleted, imageShortDescrption, imageLongDescription); - - System.out.println("Created imageData"); - - FtpCredentials ftpCredentials = client.submitImage(data.sessionId, imageData); - System.out.println("Got FTP credentials. User: " + ftpCredentials.username + ", password: " + ftpCredentials.password); - - FTPClient FtpClient = new FTPClient(); - String host = "localhost"; - int port = 2221; - String user = ftpCredentials.username; - String password = ftpCredentials.password; - String fileName = "/home/nils/file_to_upload.bin"; - - try { - FtpClient.connect(host, port); - System.out.println("Connected to " + host + ":" + port + ". Reply code: " + FtpClient.getReplyCode()); + statusIsValid, statusIsDeleted, imageShortDescrption, imageLongDescription ); + + System.out.println( "Created imageData" ); + + FtpCredentials ftpCredentials = client.submitImage( data.sessionId, imageData ); + System.out.println( "Got FTP credentials. User: " + ftpCredentials.username + ", password: " + ftpCredentials.password ); + + FTPClient FtpClient = new FTPClient(); + String host = "localhost"; + int port = 2221; + String user = ftpCredentials.username; + String password = ftpCredentials.password; + String fileName = "/home/nils/file_to_upload.bin"; + + try { + FtpClient.connect( host, port ); + System.out.println( "Connected to " + host + ":" + port + ". Reply code: " + FtpClient.getReplyCode() ); if ( !FTPReply.isPositiveCompletion( FtpClient.getReplyCode() ) ) { - ConnectException ce = new ConnectException("No positive reply code."); + ConnectException ce = new ConnectException( "No positive reply code." ); throw ce; } - if ( !FtpClient.login(user, password) ) { - ConnectException ce = new ConnectException("Could not login."); + if ( !FtpClient.login( user, password ) ) { + ConnectException ce = new ConnectException( "Could not login." ); throw ce; } - System.out.println("Logged in with user: " + user); - FtpClient.setFileType(FTP.BINARY_FILE_TYPE); + System.out.println( "Logged in with user: " + user ); + FtpClient.setFileType( FTP.BINARY_FILE_TYPE ); FtpClient.enterLocalPassiveMode(); - System.out.println("Entered PASSIVE MODE"); - InputStream input = new FileInputStream(fileName); - System.out.print("Starting file upload ... "); - FtpClient.storeFile("xcvb.vmdk", input); - System.out.println("done."); + System.out.println( "Entered PASSIVE MODE" ); + InputStream input = new FileInputStream( fileName ); + System.out.print( "Starting file upload ... " ); + FtpClient.storeFile( "xcvb.vmdk", input ); + System.out.println( "done." ); FtpClient.noop(); + client.finshedUpload( data.sessionId, imageData ); } finally { - if (FtpClient.isConnected()) { + if ( FtpClient.isConnected() ) { try { FtpClient.logout(); FtpClient.disconnect(); - } catch (IOException e) { + } catch ( IOException e ) { e.printStackTrace(); } } - } - - } - - public void testSha512_Crypt() - { - Sha512Crypt.selfTest(); - } + } + + } + + public void testSha512_Crypt() + { + Sha512Crypt.selfTest(); + } } |