From f71e8a5bcd2d7f85f58fedf3f6ea8dc8c7f89b63 Mon Sep 17 00:00:00 2001 From: Nils Schwabe Date: Wed, 23 Apr 2014 15:10:36 +0200 Subject: Reformat all files with simon's new layout --- src/main/java/org/openslx/imagemaster/App.java | 47 ++--- src/main/java/org/openslx/imagemaster/Globals.java | 172 +++++++++------- .../java/org/openslx/imagemaster/db/DbImage.java | 52 ++--- .../org/openslx/imagemaster/db/DbSatellite.java | 23 ++- .../java/org/openslx/imagemaster/db/DbUser.java | 45 +++-- .../org/openslx/imagemaster/db/ImageProcessor.java | 78 ++++---- .../java/org/openslx/imagemaster/db/LdapUser.java | 103 +++++----- .../java/org/openslx/imagemaster/db/MySQL.java | 16 +- .../org/openslx/imagemaster/server/ApiServer.java | 152 +++++++------- .../server/FtpCredentialsScheduler.java | 2 +- .../imagemaster/server/MasterFtpServer.java | 8 +- .../openslx/imagemaster/server/MasterFtplet.java | 35 ++-- .../serversession/ServerAuthenticator.java | 39 ++-- .../imagemaster/serversession/ServerSession.java | 17 +- .../serversession/ServerSessionManager.java | 8 +- .../imagemaster/serversession/ServerUser.java | 6 +- .../openslx/imagemaster/session/Authenticator.java | 26 +-- .../imagemaster/session/SessionManager.java | 1 + .../java/org/openslx/imagemaster/session/User.java | 1 - .../thrift/server/ImageServerHandler.java | 36 ++-- .../thrift/server/TBinaryProtocolSafe.java | 6 +- .../java/org/openslx/imagemaster/util/Hash.java | 26 +-- .../org/openslx/imagemaster/util/RandomString.java | 22 ++- .../java/org/openslx/imagemaster/util/Util.java | 33 ++-- src/test/java/org/openslx/imagemaster/AppTest.java | 220 +++++++++++---------- 25 files changed, 646 insertions(+), 528 deletions(-) diff --git a/src/main/java/org/openslx/imagemaster/App.java b/src/main/java/org/openslx/imagemaster/App.java index c0f7a34..989f39e 100644 --- a/src/main/java/org/openslx/imagemaster/App.java +++ b/src/main/java/org/openslx/imagemaster/App.java @@ -9,59 +9,62 @@ import org.openslx.imagemaster.Globals.PropInt; import org.openslx.imagemaster.server.FtpCredentialsScheduler; 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 servers = new ArrayList<>(); - public static void main(String[] args) { + public static void main( String[] args ) + { // Init logging - log.info("Starting Application"); + log.info( "Starting Application" ); // Load properties try { 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 ( !Globals.propertiesValid() ) { + log.error( "Config file contains errors." ); + System.exit( 1 ); } - } catch (IOException e) { - log.error("Could not load config file. Quitting."); - System.exit(1); + } catch ( IOException e ) { + log.error( "Could not load config file. Quitting." ); + System.exit( 1 ); } - log.info("Loaded config file"); + 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 Globals.ftpServer.init( Globals.getPropertyInt( PropInt.FTPPORT ) ); Thread f; - f = new Thread(Globals.ftpServer, "FtpServer"); - servers.add(f); + f = new Thread( Globals.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 1f0b876..6f3524b 100644 --- a/src/main/java/org/openslx/imagemaster/Globals.java +++ b/src/main/java/org/openslx/imagemaster/Globals.java @@ -8,43 +8,51 @@ import java.util.Properties; import org.apache.commons.lang3.StringUtils; import org.openslx.imagemaster.server.MasterFtpServer; -public class Globals { +public class Globals +{ + private static final Properties properties = new Properties(); private static boolean loadedProperties = false; - + public static final MasterFtpServer ftpServer = new MasterFtpServer(); - - public static enum PropInt { + + public static enum PropInt + { LDAPPORT, SESSIONTIMEOUTUSER, SESSIONTIMEOUTSERVER, FTPPORT, FTPTIMEOUT } - - public static enum PropString { + + public static enum PropString + { IMAGEDIR, LDAPHOST, LDAPBINDQUERY, LDAPSEARCHBASEDN, LDAPSEARCHFILTER, FTPBASEDIR } - - public static enum PropBool { + + 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; - + 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(); - + 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 + + 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() @@ -56,79 +64,111 @@ public class Globals { || Globals.getPropertyString( PropString.LDAPSEARCHFILTER ).isEmpty() || Globals.getPropertyString( PropString.FTPBASEDIR ) == null || Globals.getPropertyString( PropString.FTPBASEDIR ).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 - ) { + || Globals.getPropertyInt( PropInt.FTPTIMEOUT ) == 0 ) { return false; } - - if (StringUtils.countMatches(Globals.getPropertyString( PropString.LDAPBINDQUERY ), "%") != 1) { + + if ( StringUtils.countMatches( Globals.getPropertyString( PropString.LDAPBINDQUERY ), "%" ) != 1 ) { return false; } - - if (StringUtils.countMatches(Globals.getPropertyString( PropString.LDAPSEARCHFILTER ), "%") != 1) { + + if ( StringUtils.countMatches( Globals.getPropertyString( PropString.LDAPSEARCHFILTER ), "%" ) != 1 ) { return false; } - + // remove "/" at the end of the path String ftp = Globals.getPropertyString( PropString.FTPBASEDIR ); - if (ftp.endsWith("/")) { - Globals.properties.put("ftp_base_dir", ftp.substring(0, ftp.length() - 1)); + 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 )); + if ( image.endsWith( "/" ) ) { + Globals.properties.put( "image_dir", image.substring( 0, image.length() - 1 ) ); } - + return true; } - - public static int getPropertyInt(Globals.PropInt props) { + + 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; + + 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; - + + if ( result == null ) + return 0; + return Integer.valueOf( result ); } - - public static String getPropertyString(Globals.PropString props) { + + 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; + + 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) { + + public static boolean getPropertyBool( Globals.PropBool props ) + { String result = null; - - switch (props) { - case LDAPSSL: result = properties.getProperty( "ldap_ssl" ); - default: result = ""; break; + + 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 de545ae..d0ac5c6 100644 --- a/src/main/java/org/openslx/imagemaster/db/ImageProcessor.java +++ b/src/main/java/org/openslx/imagemaster/db/ImageProcessor.java @@ -7,49 +7,51 @@ 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 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.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()) { + 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.getPropertyString( Globals.PropString.FTPBASEDIR ) + "/" + 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; } @@ -57,31 +59,31 @@ public class ImageProcessor { * 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 0a18565..08eb127 100644 --- a/src/main/java/org/openslx/imagemaster/db/LdapUser.java +++ b/src/main/java/org/openslx/imagemaster/db/LdapUser.java @@ -28,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 ]; } - + } /** @@ -52,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(Globals.getPropertyInt( Globals.PropInt.LDAPPORT )); - ldapConfig.setLdapHost(Globals.getPropertyString( Globals.PropString.LDAPHOST )); - ldapConfig.setUseSsl(Globals.getPropertyBool( PropBool.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.getPropertyString( PropString.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.getPropertyString( Globals.PropString.LDAPSEARCHBASEDN ), - Globals.getPropertyString( Globals.PropString.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 f4511fe..30fb0a8 100644 --- a/src/main/java/org/openslx/imagemaster/server/ApiServer.java +++ b/src/main/java/org/openslx/imagemaster/server/ApiServer.java @@ -39,8 +39,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 +51,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 +72,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 = Globals.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 ) ) { + Globals.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.getPropertyString( Globals.PropString.FTPBASEDIR ) + "/" + username); + String username = Globals.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); - + Globals.ftpServer.removeUser( username ); + log.info( "Removed user: " + username ); + + ImageProcessor.processImageAfterUpload( username, list[0].getName() ); + + Globals.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 index 88e70f8..c5fad4f 100644 --- a/src/main/java/org/openslx/imagemaster/server/FtpCredentialsScheduler.java +++ b/src/main/java/org/openslx/imagemaster/server/FtpCredentialsScheduler.java @@ -30,7 +30,7 @@ public class FtpCredentialsScheduler extends TimerTask 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."); + log.info( username + "'s files are too old. Deleting him and his folder." ); Util.deleteFolder( dir ); Globals.ftpServer.removeUser( sessionId ); } diff --git a/src/main/java/org/openslx/imagemaster/server/MasterFtpServer.java b/src/main/java/org/openslx/imagemaster/server/MasterFtpServer.java index 5f5dd79..f68e909 100644 --- a/src/main/java/org/openslx/imagemaster/server/MasterFtpServer.java +++ b/src/main/java/org/openslx/imagemaster/server/MasterFtpServer.java @@ -24,7 +24,6 @@ import org.openslx.imagemaster.util.RandomString; public class MasterFtpServer implements Runnable { - private static Logger log = Logger.getLogger( MasterFtpServer.class ); private FtpServer server; private UserManager userManager; @@ -34,10 +33,11 @@ public class MasterFtpServer implements Runnable public final HashMap timeouts = new HashMap<>(); private boolean ini = false; - public void init(int port) + public void init( int port ) { - if (ini) return; - + if ( ini ) + return; + FtpServerFactory serverFactory = new FtpServerFactory(); ListenerFactory factory = new ListenerFactory(); // set the port of the listener diff --git a/src/main/java/org/openslx/imagemaster/server/MasterFtplet.java b/src/main/java/org/openslx/imagemaster/server/MasterFtplet.java index 559197c..a8c1cbe 100644 --- a/src/main/java/org/openslx/imagemaster/server/MasterFtplet.java +++ b/src/main/java/org/openslx/imagemaster/server/MasterFtplet.java @@ -11,45 +11,52 @@ import org.apache.ftpserver.ftplet.FtpletContext; import org.apache.ftpserver.ftplet.FtpletResult; import org.apache.log4j.Logger; -public class MasterFtplet implements Ftplet { - private static Logger log = Logger.getLogger(Ftplet.class); +public class MasterFtplet implements Ftplet +{ + private static Logger log = Logger.getLogger( Ftplet.class ); @Override - public void init(FtpletContext ftpletContext) throws FtpException { + 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 { + 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 authenticatingServers = new HashMap(); @@ -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 633788b..355fc0b 100644 --- a/src/main/java/org/openslx/imagemaster/serversession/ServerSession.java +++ b/src/main/java/org/openslx/imagemaster/serversession/ServerSession.java @@ -5,11 +5,10 @@ import org.openslx.imagemaster.Globals.PropInt; /** * Holds the session id of the server and manages the timeout. - * @author nils - * + * */ -public class ServerSession { - +public class ServerSession +{ private static final long TIMEOUT = Long.valueOf( Globals.getPropertyInt( PropInt.SESSIONTIMEOUTSERVER ) ) * 1000L; private long timeOut = 0; @@ -32,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/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 60ae19a..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,11 +16,11 @@ 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..."); + 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 f30ba00..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,13 +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; @@ -76,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?" ); @@ -114,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 md5hash = new ThreadLocal() { + @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 sha256hash = new ThreadLocal() { + @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 fecf9ac..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,59 +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(); + } } -- cgit v1.2.3-55-g7522