From acf091453038b827aafba625155045449dd53bab Mon Sep 17 00:00:00 2001 From: Giuliano Rasper Date: Mon, 19 Oct 2020 19:18:03 +0200 Subject: [PATCH 1/2] SQL Exceptions converted to IllegalArgumentExceptions so that communication hands the information to frontend. --- .../main/java/database/DB_UserManager.java | 5 +- backend/src/main/java/main/Conference.java | 203 +++++++++--------- .../src/main/java/user/DB_UserManagement.java | 3 +- 3 files changed, 100 insertions(+), 111 deletions(-) diff --git a/backend/src/main/java/database/DB_UserManager.java b/backend/src/main/java/database/DB_UserManager.java index a61b4fb..3534feb 100644 --- a/backend/src/main/java/database/DB_UserManager.java +++ b/backend/src/main/java/database/DB_UserManager.java @@ -461,7 +461,7 @@ public List getAllGroupsFromUser() { * @return True, iff the attendee was added correctly. */ @Override - public boolean addAttendee(Attendee a, String password, String token) { + public void addAttendee(Attendee a, String password, String token) throws SQLException { Connection connection = this.openConnection(); String sqlstatement = "INSERT INTO users(userID, fullname, username, password, " + "token, email, groups, function, residence, isAdmin, present)" @@ -482,11 +482,10 @@ public boolean addAttendee(Attendee a, String password, String token) { } catch (SQLException ex) { System.err.println("An exception occurred while adding a new attendee."); System.err.println(ex.getMessage()); - return false; + throw ex; } finally { this.closeConnection(connection); } - return true; } /** diff --git a/backend/src/main/java/main/Conference.java b/backend/src/main/java/main/Conference.java index f45e6d9..32f1ffb 100644 --- a/backend/src/main/java/main/Conference.java +++ b/backend/src/main/java/main/Conference.java @@ -33,6 +33,7 @@ import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; +import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -155,13 +156,13 @@ public Conference(String name, String organizer, long startsAt, long endsAt, Has File database = new File(databasePath); - if(database.getAbsolutePath().startsWith(new File(documentsPath).getAbsolutePath())) { + if (database.getAbsolutePath().startsWith(new File(documentsPath).getAbsolutePath())) { System.err.println("Please do not store the database inside the documents folder"); System.exit(1); } - if(database.exists() && cleanStart) { + if (database.exists() && cleanStart) { database.delete(); } @@ -172,11 +173,11 @@ public Conference(String name, String organizer, long startsAt, long endsAt, Has initVotes(); - if(database.exists() && cleanStart) { + if (database.exists() && cleanStart) { File[] directoryListing = new File(documentsPath).listFiles(); - for(int i = 0; directoryListing != null && i < directoryListing.length; i++) { + for (int i = 0; directoryListing != null && i < directoryListing.length; i++) { Document d = db_documentManagement.getDocument(directoryListing[i].getName()); - if(d == null) { + if (d == null) { directoryListing[i].delete(); } else { documents.put(d.getName(), d); @@ -186,11 +187,11 @@ public Conference(String name, String organizer, long startsAt, long endsAt, Has tmpDir = new File(System.getProperty("user.dir") + "/tmp/conference"); - if(!tmpDir.exists()) { + if (!tmpDir.exists()) { tmpDir.mkdirs(); } - long conferenceDuration = endsAt - System.currentTimeMillis()/1000; + long conferenceDuration = endsAt - System.currentTimeMillis() / 1000; Timer ActiveTimer = new Timer(); ActiveTimer.schedule(new TimerTask() { @Override @@ -230,17 +231,17 @@ private void initDocuments() { db_documentManagement = new DB_DocumentManager(databasePath); File documentsFolder = new File(documentsPath); - if(!documentsFolder.exists() && !documentsFolder.mkdir()) { + if (!documentsFolder.exists() && !documentsFolder.mkdir()) { throw new IllegalArgumentException("Could not create directory " + documentsPath); } - if(documentsFolder.exists() && !documentsFolder.isDirectory()) { + if (documentsFolder.exists() && !documentsFolder.isDirectory()) { throw new IllegalArgumentException("Could not create directory " + documentsPath + " , because a file with that name already exists"); } - if(documentsFolder.exists() && documentsFolder.isDirectory()) { + if (documentsFolder.exists() && documentsFolder.isDirectory()) { File[] directoryListing = documentsFolder.listFiles(); - for(int i = 0; i < directoryListing.length; i++) { + for (int i = 0; i < directoryListing.length; i++) { Document d = db_documentManagement.getDocument(directoryListing[i].getName()); - if(d == null) { + if (d == null) { directoryListing[i].delete(); } else { documents.put(d.getName(), d); @@ -278,12 +279,12 @@ public boolean logoutNonAdmins(Boolean newpw) { try { attendeeLock.lock(); boolean success = true; - for(Attendee a : db_userManagement.getAllAttendees()) { - if(isAdmin(a.getID())) { + for (Attendee a : db_userManagement.getAllAttendees()) { + if (isAdmin(a.getID())) { continue; } a.logout(); - if(newpw) { + if (newpw) { success = db_userManagement.logoutUser(a.getID(), gen.generatePassword(), generateToken()) && success; } else { success = db_userManagement.logoutUser(a.getID(), null, null) && success; @@ -302,7 +303,7 @@ public boolean logoutNonAdmins(Boolean newpw) { private String generateToken() { String token = gen.generateToken(); - while(db_userManagement.checkToken(token) != TokenResponse.TokenDoesNotExist) { + while (db_userManagement.checkToken(token) != TokenResponse.TokenDoesNotExist) { token = gen.generateToken(); } return token; @@ -320,10 +321,10 @@ public void addRequest(Request request) { try { requestLock.lock(); - if(requests.containsKey(request.ID)) { + if (requests.containsKey(request.ID)) { throw new IllegalArgumentException(); } - if(!db_requestManagement.addRequest(request)) { + if (!db_requestManagement.addRequest(request)) { throw new IllegalArgumentException(); } requests.put(request.ID, request); @@ -337,7 +338,6 @@ public void addRequest(Request request) { * Get specific Request from the Database * * @param ID of the Request - * * @return Request */ @Override @@ -376,7 +376,7 @@ public void addAdmin(Admin a) { adminLock.lock(); attendeeLock.lock(); volatileUserNames.remove(a.getUserName()); - if(!db_userManagement.addAdmin(a, gen.generatePassword(), generateToken())) { + if (!db_userManagement.addAdmin(a, gen.generatePassword(), generateToken())) { throw new IllegalArgumentException("Database addition failed"); } admins.put(a.getID(), a); @@ -405,7 +405,6 @@ public List getAllAdmins() { * Read all personal Data from Admin with AdminId ID and return an Admin Object containing the Data. * * @param ID AdminId - * * @return Admin */ @Override @@ -427,12 +426,12 @@ public Admin getAdminPersonalData(int ID) { public void removeAdmin(int ID) { try { adminLock.lock(); - if(admins.get(ID) == null) { + if (admins.get(ID) == null) { throw new IllegalArgumentException("Admin not found"); } else { admins.remove(ID); } - if(!db_userManagement.removeUser(ID)) { + if (!db_userManagement.removeUser(ID)) { throw new IllegalArgumentException("Admin can not be removed for unknown reasons"); } } finally { @@ -449,12 +448,12 @@ public void removeAdmin(int ID) { public void logoutAdmin(int ID) { try { adminLock.lock(); - if(admins.get(ID) == null) { + if (admins.get(ID) == null) { throw new IllegalArgumentException("Admin not found"); } else { admins.get(ID).logout(); } - if(!(db_userManagement.logoutUser(ID, gen.generatePassword(), generateToken()))) { + if (!(db_userManagement.logoutUser(ID, gen.generatePassword(), generateToken()))) { throw new IllegalArgumentException("Admin can not be logged out for unknown reasons"); } } finally { @@ -472,10 +471,10 @@ public void logoutAdmin(int ID) { public void editAdmin(int ID, Admin a) { try { adminLock.lock(); - if(!admins.containsKey(ID)) { + if (!admins.containsKey(ID)) { throw new IllegalArgumentException("Admin not found"); } - if(!db_userManagement.editAdmin(a)) { + if (!db_userManagement.editAdmin(a)) { throw new IllegalArgumentException("Admin can not be edited for unknown reasons"); } admins.replace(ID, a); @@ -492,7 +491,7 @@ public void deleteAllAdmins() { try { adminLock.lock(); admins = new HashMap(); - if(!db_userManagement.removeAllAdmins()) { + if (!db_userManagement.removeAllAdmins()) { throw new IllegalArgumentException("Can´t delete all Admins in the Database"); } } finally { @@ -507,11 +506,11 @@ public void addAdmin(Admin a, String pwd) { adminLock.lock(); AtomicBoolean alreadyExists = new AtomicBoolean(false); db_userManagement.getAllAttendees().forEach(ad -> { - if(ad.getID() == a.getID()) { + if (ad.getID() == a.getID()) { alreadyExists.set(true); } }); - if(!alreadyExists.get() && !db_userManagement.addAdmin(a, pwd, generateToken())) { + if (!alreadyExists.get() && !db_userManagement.addAdmin(a, pwd, generateToken())) { throw new IllegalArgumentException("Database addition failed"); } admins.put(a.getID(), a); @@ -527,13 +526,17 @@ public void addAttendee(Attendee a, String pwd) { adminLock.lock(); AtomicBoolean alreadyExists = new AtomicBoolean(false); db_userManagement.getAllAttendees().forEach(ad -> { - if(ad.getID() == a.getID()) { + if (ad.getID() == a.getID()) { alreadyExists.set(true); } }); - if(!alreadyExists.get() && !db_userManagement.addAttendee(a, pwd, generateToken())) { - throw new IllegalArgumentException("Database addition failed"); + if (alreadyExists.get()) { + throw new IllegalArgumentException("Failed Adding Attendee. User ID already exists."); + } else { + db_userManagement.addAttendee(a, pwd, generateToken()); } + } catch (SQLException ex) { + throw new IllegalArgumentException(ex.getMessage()); } finally { adminLock.unlock(); } @@ -550,10 +553,9 @@ public void addAttendee(Attendee a) { adminLock.lock(); attendeeLock.lock(); volatileUserNames.remove(a.getUserName()); - if(!db_userManagement.addAttendee(a, gen.generatePassword(), generateToken())) { - throw new IllegalArgumentException("Attendee can not be edited for unknown reasons"); - } - + db_userManagement.addAttendee(a, gen.generatePassword(), generateToken()); + } catch (SQLException ex) { + throw new IllegalArgumentException(ex.getMessage()); } finally { attendeeLock.unlock(); adminLock.unlock(); @@ -579,7 +581,6 @@ public List getAllAttendees() { * Read specific Attendee Data from Attendee with AttendeeId unserID and return them. * * @param userID AttendeeId - * * @return Attendee */ @Override @@ -603,19 +604,19 @@ public void removeAttendee(int userID) { try { attendeeLock.lock(); requestLock.lock(); - if(!db_userManagement.removeUser(userID)) { + if (!db_userManagement.removeUser(userID)) { throw new IllegalArgumentException("Attendee can not be removed for unknown reasons"); } - if(!db_requestManagement.removeRequest(userID)) { + if (!db_requestManagement.removeRequest(userID)) { throw new IllegalArgumentException("Attendees requests can not be removed for unknown reasons"); } List toRemove = new ArrayList<>(); requests.forEach((i, r) -> { - if(r.getRequester().getID() == userID) { + if (r.getRequester().getID() == userID) { toRemove.add(i); } }); - for(Integer i : toRemove) { + for (Integer i : toRemove) { requests.remove(i); } } finally { @@ -633,7 +634,7 @@ public void removeAttendee(int userID) { public void logoutUser(int userID) { try { attendeeLock.lock(); - if(!db_userManagement.logoutUser(userID, gen.generatePassword(), generateToken())) { + if (!db_userManagement.logoutUser(userID, gen.generatePassword(), generateToken())) { throw new IllegalArgumentException("Attendee can not be logged out for unknown reasons"); } } finally { @@ -650,7 +651,7 @@ public void logoutUser(int userID) { public void editAttendee(Attendee attendee) { try { attendeeLock.lock(); - if(!db_userManagement.editAttendee(attendee)) { + if (!db_userManagement.editAttendee(attendee)) { throw new IllegalArgumentException("Attendee could not be edited for unknown reasons"); } } finally { @@ -669,7 +670,7 @@ public void generateNewUserPassword(int userID) { attendeeLock.lock(); String password = gen.generatePassword(); System.out.println("Generated password:" + password + "for user " + userID); - if(!db_userManagement.storeNewPassword(userID, password)) { + if (!db_userManagement.storeNewPassword(userID, password)) { throw new IllegalArgumentException(); } } finally { @@ -686,7 +687,7 @@ public void generateNewUserPassword(int userID) { public void generateNewUserToken(int userID) { try { attendeeLock.lock(); - if(!db_userManagement.storeNewToken(userID, generateToken())) { + if (!db_userManagement.storeNewToken(userID, generateToken())) { throw new IllegalArgumentException(); } } finally { @@ -702,13 +703,13 @@ public void generateAllMissingUserPasswords() { try { attendeeLock.lock(); boolean success = true; - for(Pair p : db_userManagement.getAllPasswords()) { - if(p.second() == null) { + for (Pair p : db_userManagement.getAllPasswords()) { + if (p.second() == null) { success = db_userManagement.storeNewPassword(p.first().getID(), gen.generatePassword()) && success; } } - if(!success) { + if (!success) { throw new IllegalArgumentException(); } } finally { @@ -720,15 +721,14 @@ public void generateAllMissingUserPasswords() { * Read Password from User with UserId userId and return it. * * @param userID UserId - * * @return Pair with User and Password */ @Override public Pair getUserPassword(int userID) { try { attendeeLock.lock(); - for(Pair p : db_userManagement.getAllPasswords()) { - if(p.first().getID() == userID) { + for (Pair p : db_userManagement.getAllPasswords()) { + if (p.first().getID() == userID) { return p; } } @@ -763,13 +763,13 @@ public boolean logoutAllUsers() { try { attendeeLock.lock(); boolean success = true; - for(Attendee a : db_userManagement.getAllAttendees()) { + for (Attendee a : db_userManagement.getAllAttendees()) { a.logout(); - success = db_userManagement.logoutUser(a.getID(), gen.generatePassword(), generateToken()) && success; + success = db_userManagement.logoutUser(a.getID(), gen.generatePassword(), generateToken()) && success; } - for(Attendee a : db_userManagement.getAllAdmins()) { + for (Attendee a : db_userManagement.getAllAdmins()) { a.logout(); - success = db_userManagement.logoutUser(a.getID(), gen.generatePassword(), generateToken()) && success; + success = db_userManagement.logoutUser(a.getID(), gen.generatePassword(), generateToken()) && success; } return success; } finally { @@ -782,7 +782,6 @@ public boolean logoutAllUsers() { * * @param userName - the username provided by the request * @param password - the password provided by the request - * * @return - A pair consisting of a {@link LoginResponse}, a token, a token, and the number of seconds until the token * should expire. * If the {@link LoginResponse} is not Valid then the second argument will be null @@ -793,7 +792,7 @@ public Pair> login(String userName, String pas adminLock.lock(); attendeeLock.lock(); Pair response = db_userManagement.checkLogin(userName, password); - if(response.first() != LoginResponse.Valid) { + if (response.first() != LoginResponse.Valid) { return new Pair<>(response.first(), null); } else { return new Pair<>(response.first(), new Pair<>(response.second(), endsAt)); @@ -808,7 +807,6 @@ public Pair> login(String userName, String pas * Read the specific UserID from a User with Token token. * * @param token Token - * * @return UserId */ @Override @@ -827,7 +825,6 @@ public int tokenToID(String token) { * Check if Admin with AdminId id is an Admin. * * @param id AdminId - * * @return true iff User is an Admin */ @Override @@ -839,7 +836,6 @@ public boolean isAdmin(int id) { * Checks the Status of the Token token. * * @param token Token - * * @return TokenResponse */ @Override @@ -847,11 +843,11 @@ public TokenResponse checkToken(String token) { try { adminLock.lock(); attendeeLock.lock(); - if(adminTokens.containsKey(token)) { + if (adminTokens.containsKey(token)) { return TokenResponse.ValidAdmin; } else { TokenResponse res = db_userManagement.checkToken(token); - if(res == TokenResponse.ValidAdmin) { + if (res == TokenResponse.ValidAdmin) { adminTokens.put(token, true); } return res; @@ -866,7 +862,6 @@ public TokenResponse checkToken(String token) { * Create an unique UserName from Name name, that isn´t stored in the Database. * * @param name Name - * * @return Username */ @Override @@ -877,7 +872,7 @@ public String getFreeUserName(String name) { name = name.replaceAll("[^A-Za-z0-9]", "."); String nameAux = name; int i = 1; - while(volatileUserNames.containsKey(nameAux) || db_userManagement.userNameAlreadyUsed(nameAux)) { + while (volatileUserNames.containsKey(nameAux) || db_userManagement.userNameAlreadyUsed(nameAux)) { nameAux = name + i; i++; } @@ -912,7 +907,6 @@ public List getExistingGroups() { * * @param username username of the user * @param present new present value of the user - * * @return */ public Boolean setPresentValue(String username, Boolean present) { @@ -934,7 +928,7 @@ public Boolean setPresentValue(String username, Boolean present) { public Boolean startVoting(Voting vote) { try { votingLock.lock(); - if(this.getActiveVoting() != null) { + if (this.getActiveVoting() != null) { return false; } vote.startVote(); @@ -980,7 +974,6 @@ public Voting getActiveVoting() { * Get created Voting with VotingId ID. * * @param ID VotingId - * * @return Voting */ @Override @@ -1045,18 +1038,17 @@ public void removeVoting(Voting voting) { * Updated a specific Voting * * @param v The updates {@link Voting}. - * * @return if the voting was updated successfully */ @Override public boolean update(Voting v) { try { votingLock.lock(); - if(v.getStatus() == VotingStatus.Closed) { + if (v.getStatus() == VotingStatus.Closed) { activeVoting = null; } - if(v.getStatus() == VotingStatus.Running) { - if(activeVoting != null) { + if (v.getStatus() == VotingStatus.Running) { + if (activeVoting != null) { return false; } else { activeVoting = v; @@ -1083,10 +1075,10 @@ public Agenda getAgenda() { @Override public void updateAgenda(Agenda newAgenda) { ConcurrentHashMap observers = this.agenda.getObservers(); - for(Map.Entry o : observers.entrySet()) { + for (Map.Entry o : observers.entrySet()) { newAgenda.register(o.getKey()); } //Two loops to avoid ConcurrentModification - for(Map.Entry o : observers.entrySet()) { + for (Map.Entry o : observers.entrySet()) { this.agenda.unregister(o.getKey()); } this.agenda = newAgenda; @@ -1109,27 +1101,27 @@ public void updateAgenda(Agenda newAgenda) { public void updateDocument(String name, String fileType, File file, boolean isCreation) { try { documentsLock.lock(); - if(file.length() > 1024 * 1024 * 500) { + if (file.length() > 1024 * 1024 * 500) { throw new IllegalArgumentException("The file is to large"); } - if(!name.endsWith(fileType)) { + if (!name.endsWith(fileType)) { throw new IllegalArgumentException("File extensions differ"); } String fullName = name; File f; - if(!documents.containsKey(fullName)) { + if (!documents.containsKey(fullName)) { f = new File(documentsPath + "/" + fullName); } else { f = documents.get(fullName).getFile(); } - if(f.exists() && isCreation) { + if (f.exists() && isCreation) { throw new IllegalArgumentException("File already exists"); } - if(!f.exists() && !isCreation) { + if (!f.exists() && !isCreation) { throw new IllegalArgumentException("File does not exist"); } try { - if(f.exists() || f.createNewFile()) { + if (f.exists() || f.createNewFile()) { f.delete(); Files.move(file.toPath(), f.toPath()); } @@ -1137,9 +1129,9 @@ public void updateDocument(String name, String fileType, File file, boolean isCr } catch (IOException e) { throw new IllegalArgumentException(e.getMessage()); } - if(isCreation) { + if (isCreation) { Document doc = new Document(f.getPath(), fullName); - if(db_documentManagement.addDocument(doc)) { + if (db_documentManagement.addDocument(doc)) { documents.put(fullName, doc); } } else { @@ -1160,14 +1152,14 @@ public void updateDocument(String name, String fileType, File file, boolean isCr public void deleteDocument(String name) { try { documentsLock.lock(); - if(!documents.containsKey(name)) { + if (!documents.containsKey(name)) { throw new IllegalArgumentException("Document does not exist"); } File f = documents.get(name).getFile(); - if(!f.delete()) { + if (!f.delete()) { throw new IllegalArgumentException("Could not remove document from server"); } - if(!db_documentManagement.deleteDocument(name)) { + if (!db_documentManagement.deleteDocument(name)) { throw new IllegalArgumentException("Could not remove the document from the database"); } documents.remove(name); @@ -1181,14 +1173,13 @@ public void deleteDocument(String name) { * Read Content from Document with DocumentName name * * @param name DocumentName - * * @return Byte List */ @Override public byte[] getDocumentContent(String name) { try { documentsLock.lock(); - if(!documents.containsKey(name)) { + if (!documents.containsKey(name)) { throw new IllegalArgumentException("file does not exist"); } @@ -1213,14 +1204,13 @@ public byte[] getDocumentContent(String name) { * Read Document Data with DocumentName name and return it. * * @param name DocumentName - * * @return Document */ @Override public Document getDocument(String name) { try { documentsLock.lock(); - if(!documents.containsKey(name)) { + if (!documents.containsKey(name)) { throw new IllegalArgumentException("Document does not exist"); } return documents.get(name); @@ -1248,13 +1238,12 @@ public List getAllDocuments() { * Read Content from Document with DocumentName name * * @param name DocumentName - * * @return File */ public File getDocumentContentAsFile(String name) { try { documentsLock.lock(); - if(!documents.containsKey(name)) { + if (!documents.containsKey(name)) { throw new IllegalArgumentException("file does not exist"); } @@ -1300,7 +1289,7 @@ public byte[] getAllQrCodes() { String sourceFile = tmpDir.getAbsolutePath() + "/qr/"; File f = new File(tmpDir.getAbsolutePath() + "/qrs.zip"); - if(f.exists()) { + if (f.exists()) { f.delete(); } @@ -1335,7 +1324,7 @@ public void generateQRCode(int attendeeId) { Attendee a = db_userManagement.getAttendeeData(attendeeId); File qrDir = new File(tmpDir.getAbsolutePath() + "/qr/"); - if(!qrDir.exists() || !qrDir.isDirectory()) { + if (!qrDir.exists() || !qrDir.isDirectory()) { generateCleanDirectory(qrDir); } @@ -1371,7 +1360,7 @@ public void generateAllQRCodes() { adminLock.lock(); attendeeLock.lock(); purgeDirectory(new File(tmpDir.getAbsolutePath() + "/qr/")); - for(Attendee a : getAllAttendees()) { + for (Attendee a : getAllAttendees()) { generateQRCode(a.getID()); } } finally { @@ -1382,22 +1371,22 @@ public void generateAllQRCodes() { } void generateCleanDirectory(File userDir) { - if(userDir.exists() && !userDir.isDirectory()) { + if (userDir.exists() && !userDir.isDirectory()) { userDir.delete(); } - if(!userDir.exists()) { + if (!userDir.exists()) { userDir.mkdir(); } else { - if(userDir.isDirectory()) { + if (userDir.isDirectory()) { purgeDirectory(userDir); } } } void purgeDirectory(File dir) { - if(!dir.exists()) return; - for(File file : dir.listFiles()) { - if(file.isDirectory()) { + if (!dir.exists()) return; + for (File file : dir.listFiles()) { + if (file.isDirectory()) { purgeDirectory(file); } file.delete(); @@ -1405,18 +1394,18 @@ void purgeDirectory(File dir) { } private void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut, boolean root) throws IOException { - if(fileToZip.isHidden()) { + if (fileToZip.isHidden()) { return; } - if(root) { + if (root) { File[] children = fileToZip.listFiles(); - for(File childFile : children) { + for (File childFile : children) { zipFile(childFile, fileName + "/" + childFile.getName(), zipOut, false); } return; } - if(fileToZip.isDirectory()) { - if(fileName.endsWith("/")) { + if (fileToZip.isDirectory()) { + if (fileName.endsWith("/")) { zipOut.putNextEntry(new ZipEntry(fileName)); zipOut.closeEntry(); } else { @@ -1424,7 +1413,7 @@ private void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut, bo zipOut.closeEntry(); } File[] children = fileToZip.listFiles(); - for(File childFile : children) { + for (File childFile : children) { zipFile(childFile, fileName + "/" + childFile.getName(), zipOut, false); } return; @@ -1435,7 +1424,7 @@ private void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut, bo zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; - while((length = fis.read(bytes)) >= 0) { + while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } fis.close(); diff --git a/backend/src/main/java/user/DB_UserManagement.java b/backend/src/main/java/user/DB_UserManagement.java index a29ced2..767a352 100644 --- a/backend/src/main/java/user/DB_UserManagement.java +++ b/backend/src/main/java/user/DB_UserManagement.java @@ -2,6 +2,7 @@ import utils.Pair; +import java.sql.SQLException; import java.util.List; @SuppressWarnings("checkstyle:typename") @@ -137,7 +138,7 @@ public interface DB_UserManagement { * * @return True, iff the attendee was added correctly. */ - boolean addAttendee(Attendee a, String password, String token); + void addAttendee(Attendee a, String password, String token) throws SQLException; /** * @return a list of all {@link Attendee}s in the database. From 43b9d6d20c7be3a3adb5fbae4d8cef4d1f5aaebe Mon Sep 17 00:00:00 2001 From: Simon Date: Mon, 19 Oct 2020 20:35:54 +0200 Subject: [PATCH 2/2] Refactored DB_UserManager functions to no longer return boolean values and adjusted usages in Conference --- .../main/java/database/DB_UserManager.java | 56 +++++------ backend/src/main/java/main/Conference.java | 99 +++++++------------ .../java/request/DB_RequestManagement.java | 4 +- .../main/java/user/AttendeeManagement.java | 2 +- .../src/main/java/user/DB_UserManagement.java | 22 ++--- 5 files changed, 70 insertions(+), 113 deletions(-) diff --git a/backend/src/main/java/database/DB_UserManager.java b/backend/src/main/java/database/DB_UserManager.java index 3534feb..1afcead 100644 --- a/backend/src/main/java/database/DB_UserManager.java +++ b/backend/src/main/java/database/DB_UserManager.java @@ -162,18 +162,17 @@ public TokenResponse checkToken(String token) { * @return true, iff the db stored the new present value correctly */ @Override - public Boolean setPresentValueofUser(String userName, Boolean present) { + public void setPresentValueofUser(String userName, Boolean present) { Connection connection = this.openConnection(); String sqlstatement = "UPDATE users SET present = ? WHERE username = ?"; try (PreparedStatement stmt = connection.prepareStatement(sqlstatement)) { stmt.setBoolean(1, present); stmt.setString(2, userName); stmt.executeUpdate(); - return true; } catch (SQLException e) { System.err.println("An exception occurred while updating Present value of a user."); System.err.println(e.getMessage()); - return false; + throw new IllegalArgumentException(e.getMessage()); } finally { this.closeConnection(connection); } @@ -218,9 +217,9 @@ public int tokenToID(String token) { * @return True, iff the user was successfully removed. */ @Override - public boolean removeUser(int userID) { + public void removeUser(int userID) { if(!this.userIDAlreadyUsed(userID)) { - return false; + throw new IllegalArgumentException("Attendee does not exist!"); } Connection connection = this.openConnection(); String sqlstatement = "DELETE FROM users WHERE userID = ?"; @@ -230,11 +229,10 @@ public boolean removeUser(int userID) { } catch (SQLException e) { System.err.println("An exception occurred while removing a user from the database."); System.err.println(e.getMessage()); - return false; + throw new IllegalArgumentException(e.getMessage()); } finally { this.closeConnection(connection); } - return true; } @@ -247,7 +245,7 @@ public boolean removeUser(int userID) { * @return True, iff the operation was successful. */ @Override - public boolean logoutUser(int userID, String pw, String token) { + public void logoutUser(int userID, String pw, String token) { Connection connection = this.openConnection(); String sqlstatement = "UPDATE users SET password = ?, token = ?, present = ? WHERE userID = ?"; try (PreparedStatement stmt = connection.prepareStatement(sqlstatement)) { @@ -267,11 +265,10 @@ public boolean logoutUser(int userID, String pw, String token) { } catch (SQLException e) { System.err.println("An exception occurred while logging out/invalidating a user."); System.err.println(e.getMessage()); - return false; + throw new IllegalArgumentException(e.getMessage()); } finally { this.closeConnection(connection); } - return true; } /** @@ -315,7 +312,7 @@ public List> getAllPasswords() { * @return True, iff the new token was successfully added to the database. */ @Override - public boolean storeNewToken(int userID, String token) { + public void storeNewToken(int userID, String token) { Connection connection = this.openConnection(); String sqlstatement = "UPDATE users SET token = ? WHERE userID = ?"; try (PreparedStatement stmt = connection.prepareStatement(sqlstatement)) { @@ -325,11 +322,10 @@ public boolean storeNewToken(int userID, String token) { } catch (SQLException e) { System.err.println("An exception occurred while storing a new user token."); System.err.println(e.getMessage()); - return false; + throw new IllegalArgumentException(e.getMessage()); } finally { this.closeConnection(connection); } - return true; } /** @@ -341,7 +337,7 @@ public boolean storeNewToken(int userID, String token) { * @return True, iff the new password was successfully added to the database. */ @Override - public boolean storeNewPassword(int userID, String password) { + public void storeNewPassword(int userID, String password) { Connection connection = this.openConnection(); String sqlstatement = "UPDATE users SET password = ? WHERE userID = ?"; try (PreparedStatement stmt = connection.prepareStatement(sqlstatement)) { @@ -351,11 +347,10 @@ public boolean storeNewPassword(int userID, String password) { } catch (SQLException e) { System.err.println("An exception occurred while storing a new user password."); System.err.println(e.getMessage()); - return false; + throw new IllegalArgumentException(e.getMessage()); } finally { this.closeConnection(connection); } - return true; } /** @@ -394,10 +389,7 @@ public boolean userNameAlreadyUsed(String userName) { @Override public boolean userIDAlreadyUsed(int id) { List ids = this.getIDs(); - if(ids.contains(id)) { - return true; - } - return false; + return ids.contains(id); } /** @@ -461,7 +453,7 @@ public List getAllGroupsFromUser() { * @return True, iff the attendee was added correctly. */ @Override - public void addAttendee(Attendee a, String password, String token) throws SQLException { + public void addAttendee(Attendee a, String password, String token) { Connection connection = this.openConnection(); String sqlstatement = "INSERT INTO users(userID, fullname, username, password, " + "token, email, groups, function, residence, isAdmin, present)" @@ -482,7 +474,7 @@ public void addAttendee(Attendee a, String password, String token) throws SQLExc } catch (SQLException ex) { System.err.println("An exception occurred while adding a new attendee."); System.err.println(ex.getMessage()); - throw ex; + throw new IllegalArgumentException(ex.getMessage()); } finally { this.closeConnection(connection); } @@ -564,7 +556,7 @@ public Attendee getAttendeeData(int userID) { * @return True, iff the Attendee was overwritten properly */ @Override - public boolean editAttendee(Attendee a) { + public void editAttendee(Attendee a) { Connection connection = this.openConnection(); String sqlstatement = "UPDATE users SET fullname = ?, " + " email = ?, " @@ -585,11 +577,10 @@ public boolean editAttendee(Attendee a) { } catch (SQLException e) { System.err.println("An exception occurred while trying to overwrite an attendee."); System.err.println(e.getMessage()); - return false; + throw new IllegalArgumentException(e.getMessage()); } finally { this.closeConnection(connection); } - return true; } /**********************************specialAdminFunctionality********************************************/ @@ -605,7 +596,7 @@ public boolean editAttendee(Attendee a) { * @return True, iff the admin was added correctly. */ @Override - public boolean addAdmin(Admin a, String password, String token) { + public void addAdmin(Admin a, String password, String token) { Connection connection = this.openConnection(); String sqlstatement = "INSERT INTO users(userID, fullname, username, password ," + "token, email, groups, function, residence, isAdmin, present)" @@ -626,11 +617,10 @@ public boolean addAdmin(Admin a, String password, String token) { } catch (SQLException ex) { System.err.println("An exception occurred while adding a new admin."); System.err.println(ex.getMessage()); - return false; + throw new IllegalArgumentException(ex.getMessage()); } finally { this.closeConnection(connection); } - return true; } /** @@ -674,7 +664,7 @@ public List getAllAdmins() { * @return True, iff the user was successfully removed. */ @Override - public boolean removeAllAdmins() { + public void removeAllAdmins() { Connection connection = this.openConnection(); String sqlstatement = "DELETE FROM users WHERE isAdmin = ?"; try (PreparedStatement stmt = connection.prepareStatement(sqlstatement)) { @@ -683,11 +673,10 @@ public boolean removeAllAdmins() { } catch (SQLException e) { System.err.println("An exception occurred while removing all admins from the database."); System.err.println(e.getMessage()); - return false; + throw new IllegalArgumentException(e.getMessage()); } finally { this.closeConnection(connection); } - return true; } /** @@ -734,7 +723,7 @@ public Admin getAdminData(int userID) { * @return True, iff the Admin was overwritten properly */ @Override - public boolean editAdmin(Admin a) { + public void editAdmin(Admin a) { Connection connection = this.openConnection(); String sqlstatement = "UPDATE users SET fullname = ? , " + "email = ? ," @@ -754,10 +743,9 @@ public boolean editAdmin(Admin a) { } catch (SQLException e) { System.err.println("An exception occurred while trying to overwrite an admin."); System.err.println(e.getMessage()); - return false; + throw new IllegalArgumentException(e.getMessage()); } finally { this.closeConnection(connection); } - return true; } } diff --git a/backend/src/main/java/main/Conference.java b/backend/src/main/java/main/Conference.java index 32f1ffb..fed3f1d 100644 --- a/backend/src/main/java/main/Conference.java +++ b/backend/src/main/java/main/Conference.java @@ -239,10 +239,10 @@ private void initDocuments() { } if (documentsFolder.exists() && documentsFolder.isDirectory()) { File[] directoryListing = documentsFolder.listFiles(); - for (int i = 0; i < directoryListing.length; i++) { - Document d = db_documentManagement.getDocument(directoryListing[i].getName()); + for (File file : directoryListing) { + Document d = db_documentManagement.getDocument(file.getName()); if (d == null) { - directoryListing[i].delete(); + file.delete(); } else { documents.put(d.getName(), d); } @@ -275,22 +275,20 @@ public void endConference() { * * @return true iff logout was successful */ - public boolean logoutNonAdmins(Boolean newpw) { + public void logoutNonAdmins(Boolean newpw) { try { attendeeLock.lock(); - boolean success = true; for (Attendee a : db_userManagement.getAllAttendees()) { if (isAdmin(a.getID())) { continue; } a.logout(); if (newpw) { - success = db_userManagement.logoutUser(a.getID(), gen.generatePassword(), generateToken()) && success; + db_userManagement.logoutUser(a.getID(), gen.generatePassword(), generateToken()); } else { - success = db_userManagement.logoutUser(a.getID(), null, null) && success; + db_userManagement.logoutUser(a.getID(), null, null); } } - return success; } finally { attendeeLock.unlock(); } @@ -322,11 +320,9 @@ public void addRequest(Request request) { try { requestLock.lock(); if (requests.containsKey(request.ID)) { - throw new IllegalArgumentException(); - } - if (!db_requestManagement.addRequest(request)) { - throw new IllegalArgumentException(); + throw new IllegalArgumentException("Request does already exist!"); } + db_requestManagement.addRequest(request); requests.put(request.ID, request); } finally { requestLock.unlock(); @@ -376,9 +372,7 @@ public void addAdmin(Admin a) { adminLock.lock(); attendeeLock.lock(); volatileUserNames.remove(a.getUserName()); - if (!db_userManagement.addAdmin(a, gen.generatePassword(), generateToken())) { - throw new IllegalArgumentException("Database addition failed"); - } + db_userManagement.addAdmin(a, gen.generatePassword(), generateToken()); admins.put(a.getID(), a); } finally { attendeeLock.unlock(); @@ -431,9 +425,7 @@ public void removeAdmin(int ID) { } else { admins.remove(ID); } - if (!db_userManagement.removeUser(ID)) { - throw new IllegalArgumentException("Admin can not be removed for unknown reasons"); - } + db_userManagement.removeUser(ID); } finally { adminLock.unlock(); } @@ -453,9 +445,7 @@ public void logoutAdmin(int ID) { } else { admins.get(ID).logout(); } - if (!(db_userManagement.logoutUser(ID, gen.generatePassword(), generateToken()))) { - throw new IllegalArgumentException("Admin can not be logged out for unknown reasons"); - } + db_userManagement.logoutUser(ID, gen.generatePassword(), generateToken()); } finally { adminLock.unlock(); } @@ -474,9 +464,7 @@ public void editAdmin(int ID, Admin a) { if (!admins.containsKey(ID)) { throw new IllegalArgumentException("Admin not found"); } - if (!db_userManagement.editAdmin(a)) { - throw new IllegalArgumentException("Admin can not be edited for unknown reasons"); - } + db_userManagement.editAdmin(a); admins.replace(ID, a); } finally { adminLock.unlock(); @@ -491,9 +479,7 @@ public void deleteAllAdmins() { try { adminLock.lock(); admins = new HashMap(); - if (!db_userManagement.removeAllAdmins()) { - throw new IllegalArgumentException("Can´t delete all Admins in the Database"); - } + db_userManagement.removeAllAdmins(); } finally { adminLock.unlock(); } @@ -510,8 +496,10 @@ public void addAdmin(Admin a, String pwd) { alreadyExists.set(true); } }); - if (!alreadyExists.get() && !db_userManagement.addAdmin(a, pwd, generateToken())) { - throw new IllegalArgumentException("Database addition failed"); + if (alreadyExists.get()){ + throw new IllegalArgumentException("Admin already exists!"); + } else{ + db_userManagement.addAdmin(a, pwd, generateToken()); } admins.put(a.getID(), a); } finally { @@ -535,8 +523,6 @@ public void addAttendee(Attendee a, String pwd) { } else { db_userManagement.addAttendee(a, pwd, generateToken()); } - } catch (SQLException ex) { - throw new IllegalArgumentException(ex.getMessage()); } finally { adminLock.unlock(); } @@ -554,8 +540,6 @@ public void addAttendee(Attendee a) { attendeeLock.lock(); volatileUserNames.remove(a.getUserName()); db_userManagement.addAttendee(a, gen.generatePassword(), generateToken()); - } catch (SQLException ex) { - throw new IllegalArgumentException(ex.getMessage()); } finally { attendeeLock.unlock(); adminLock.unlock(); @@ -604,12 +588,9 @@ public void removeAttendee(int userID) { try { attendeeLock.lock(); requestLock.lock(); - if (!db_userManagement.removeUser(userID)) { - throw new IllegalArgumentException("Attendee can not be removed for unknown reasons"); - } - if (!db_requestManagement.removeRequest(userID)) { - throw new IllegalArgumentException("Attendees requests can not be removed for unknown reasons"); - } + db_userManagement.removeUser(userID); + db_requestManagement.removeRequest(userID); + List toRemove = new ArrayList<>(); requests.forEach((i, r) -> { if (r.getRequester().getID() == userID) { @@ -634,9 +615,7 @@ public void removeAttendee(int userID) { public void logoutUser(int userID) { try { attendeeLock.lock(); - if (!db_userManagement.logoutUser(userID, gen.generatePassword(), generateToken())) { - throw new IllegalArgumentException("Attendee can not be logged out for unknown reasons"); - } + db_userManagement.logoutUser(userID, gen.generatePassword(), generateToken()); } finally { attendeeLock.unlock(); } @@ -651,9 +630,7 @@ public void logoutUser(int userID) { public void editAttendee(Attendee attendee) { try { attendeeLock.lock(); - if (!db_userManagement.editAttendee(attendee)) { - throw new IllegalArgumentException("Attendee could not be edited for unknown reasons"); - } + db_userManagement.editAttendee(attendee); } finally { attendeeLock.unlock(); } @@ -670,9 +647,8 @@ public void generateNewUserPassword(int userID) { attendeeLock.lock(); String password = gen.generatePassword(); System.out.println("Generated password:" + password + "for user " + userID); - if (!db_userManagement.storeNewPassword(userID, password)) { - throw new IllegalArgumentException(); - } + + db_userManagement.storeNewPassword(userID, password); } finally { attendeeLock.unlock(); } @@ -687,9 +663,7 @@ public void generateNewUserPassword(int userID) { public void generateNewUserToken(int userID) { try { attendeeLock.lock(); - if (!db_userManagement.storeNewToken(userID, generateToken())) { - throw new IllegalArgumentException(); - } + db_userManagement.storeNewToken(userID, generateToken()); } finally { attendeeLock.unlock(); } @@ -702,16 +676,12 @@ public void generateNewUserToken(int userID) { public void generateAllMissingUserPasswords() { try { attendeeLock.lock(); - boolean success = true; + for (Pair p : db_userManagement.getAllPasswords()) { if (p.second() == null) { - success = db_userManagement.storeNewPassword(p.first().getID(), gen.generatePassword()) && success; + db_userManagement.storeNewPassword(p.first().getID(), gen.generatePassword()); } } - - if (!success) { - throw new IllegalArgumentException(); - } } finally { attendeeLock.unlock(); } @@ -732,7 +702,7 @@ public Pair getUserPassword(int userID) { return p; } } - throw new IllegalArgumentException(); + throw new IllegalArgumentException("Attendee does not exist!"); } finally { attendeeLock.unlock(); } @@ -759,19 +729,17 @@ public List> getAllUsersPasswords() { * @return true iff logout was successful */ @Override - public boolean logoutAllUsers() { + public void logoutAllUsers() { try { attendeeLock.lock(); - boolean success = true; for (Attendee a : db_userManagement.getAllAttendees()) { a.logout(); - success = db_userManagement.logoutUser(a.getID(), gen.generatePassword(), generateToken()) && success; + db_userManagement.logoutUser(a.getID(), gen.generatePassword(), generateToken()); } for (Attendee a : db_userManagement.getAllAdmins()) { a.logout(); - success = db_userManagement.logoutUser(a.getID(), gen.generatePassword(), generateToken()) && success; + db_userManagement.logoutUser(a.getID(), gen.generatePassword(), generateToken()); } - return success; } finally { attendeeLock.unlock(); } @@ -909,11 +877,12 @@ public List getExistingGroups() { * @param present new present value of the user * @return */ - public Boolean setPresentValue(String username, Boolean present) { + public void setPresentValue(String username, Boolean present) { try { adminLock.lock(); attendeeLock.lock(); - return db_userManagement.setPresentValueofUser(username, present); + + db_userManagement.setPresentValueofUser(username, present); } finally { attendeeLock.unlock(); adminLock.unlock(); diff --git a/backend/src/main/java/request/DB_RequestManagement.java b/backend/src/main/java/request/DB_RequestManagement.java index ca19b45..7a0d14f 100644 --- a/backend/src/main/java/request/DB_RequestManagement.java +++ b/backend/src/main/java/request/DB_RequestManagement.java @@ -12,7 +12,7 @@ public interface DB_RequestManagement extends RequestObserver { * * @return True, iff the {@link Request} was successfully added. */ - boolean addRequest(Request req); + void addRequest(Request req); /** * Reconstructs a given {@link Request} from the database. @@ -44,5 +44,5 @@ public interface DB_RequestManagement extends RequestObserver { * * @return True, iff the requests was successfully removed. */ - boolean removeRequest(int userID); + void removeRequest(int userID); } diff --git a/backend/src/main/java/user/AttendeeManagement.java b/backend/src/main/java/user/AttendeeManagement.java index 84aeac9..7e28867 100644 --- a/backend/src/main/java/user/AttendeeManagement.java +++ b/backend/src/main/java/user/AttendeeManagement.java @@ -28,6 +28,6 @@ public interface AttendeeManagement { List> getAllUsersPasswords(); - boolean logoutAllUsers(); + void logoutAllUsers(); } diff --git a/backend/src/main/java/user/DB_UserManagement.java b/backend/src/main/java/user/DB_UserManagement.java index 767a352..0725386 100644 --- a/backend/src/main/java/user/DB_UserManagement.java +++ b/backend/src/main/java/user/DB_UserManagement.java @@ -36,7 +36,7 @@ public interface DB_UserManagement { * * @return true, iff the db stored the new present value correctly */ - Boolean setPresentValueofUser(String userName, Boolean present); + void setPresentValueofUser(String userName, Boolean present); /** * Converts a token to a user ID. @@ -56,7 +56,7 @@ public interface DB_UserManagement { * * @return True, iff the user was successfully removed. */ - boolean removeUser(int userID); + void removeUser(int userID); /** * This method logs out a user in the database. This method must not delete the entry but should indicate that the @@ -68,7 +68,7 @@ public interface DB_UserManagement { * * @return True, iff the operation was successful. */ - boolean logoutUser(int userID, String pw, String token); + void logoutUser(int userID, String pw, String token); /** * Returns a list of all passwords to be handed out to the users, combined with their ID. @@ -85,7 +85,7 @@ public interface DB_UserManagement { * * @return True, iff the new token was successfully added to the database. */ - boolean storeNewToken(int userID, String token); + void storeNewToken(int userID, String token); /** * Overwrites the password of the user, in case there was a problem with the device. @@ -95,7 +95,7 @@ public interface DB_UserManagement { * * @return True, iff the new password was successfully added to the database. */ - boolean storeNewPassword(int userID, String password); + void storeNewPassword(int userID, String password); /** * This methods checks whether a username was already used to enable unique username creation. @@ -138,7 +138,7 @@ public interface DB_UserManagement { * * @return True, iff the attendee was added correctly. */ - void addAttendee(Attendee a, String password, String token) throws SQLException; + void addAttendee(Attendee a, String password, String token); /** * @return a list of all {@link Attendee}s in the database. @@ -161,7 +161,7 @@ public interface DB_UserManagement { * * @return True, iff the Attendee was overwritten properly */ - boolean editAttendee(Attendee a); + void editAttendee(Attendee a); /** * Adds a new {@link Admin} to the database. @@ -172,7 +172,7 @@ public interface DB_UserManagement { * * @return True, iff the admin was added correctly. */ - boolean addAdmin(Admin a, String password, String token); + void addAdmin(Admin a, String password, String token); /** * @return a list of all {@link Admin}s in the database. @@ -182,9 +182,9 @@ public interface DB_UserManagement { /** * This methods deletes all admins in the database. * - * @return True, iff the user was successfully removed. + * @return True, iff the admins were successfully removed. */ - boolean removeAllAdmins(); + void removeAllAdmins(); /** * Returns the {@link Admin} with the given userID. @@ -202,5 +202,5 @@ public interface DB_UserManagement { * * @return True, iff the Admin was overwritten properly */ - boolean editAdmin(Admin a); + void editAdmin(Admin a); } \ No newline at end of file