Code with Misuse: |
class SocialNetworkDatabaseBoards {
/**
* Transactional method that creates a board.
* Assumes that the user is an admin.
* 1) Checks that the user has permission to create a board
* 2) It creates a reference to the board in the "main" database, and adds this
* user as an admin.
* 3) It creates a database to store the board's regions, posts, etc.
* @throws IOException
*/
public static String createBoard(Connection conn, String createdBy, String boardName)
throws IOException {
/**AUTHORIZATION CHECK **/
/**User must be an admin to create a board**/
if (!DatabaseAdmin.isAdmin(conn, createdBy)) {
return "print Error: Cannot create a board with the name \"" + boardName
+ "\".";
}
//PreparedStatement rolePstmt = null;
PreparedStatement insertBoardPstmt = null;
PreparedStatement addAdminPstmt = null;
ResultSet idresult = null;
int firstsuccess = 0; //insertBoard success
boolean secondsuccess = false; //create board db success
int thirdsuccess = 0; //add admin success
boolean sqlex = false;
String sqlexmsg = "";
String insertBoard = "INSERT INTO main.boards VALUES (?, ?)";
String insertAdmin = "INSERT INTO main.boardadmins VALUES (?, ?)";
try {
conn.setAutoCommit(false);
insertBoardPstmt = conn.prepareStatement(insertBoard);
addAdminPstmt = conn.prepareStatement(insertAdmin);
insertBoardPstmt.setString(1, boardName);
insertBoardPstmt.setString(2, createdBy);
firstsuccess = insertBoardPstmt.executeUpdate();
if (firstsuccess == 1) { /*1 row successfully inserted*/
secondsuccess = createBoardDatabase(conn, boardName);
if (secondsuccess) {
addAdminPstmt.setString(1, boardName);
addAdminPstmt.setString(2, createdBy);
thirdsuccess = addAdminPstmt.executeUpdate();
if (thirdsuccess == 1) {
conn.commit();
}
else {
conn.rollback();
}
}
else {
conn.rollback();
}
}
else {
conn.rollback();
}
}
catch (SQLException e) {
DBManager.rollback(conn);
/* The error code for a duplicate key insertion => Must be for board name*/
if (e.getErrorCode() == DBManager.DUPLICATE_KEY_CODE) {
sqlexmsg = "print A board already exists with that name. Try a different name.";
}
else {
e.printStackTrace();
sqlexmsg = "print Error: Connection error. Contact the admin.";
}
sqlex = true;
}
catch (FileNotFoundException fnfe) {
DBManager.rollback(conn);
fnfe.printStackTrace();
}
finally {
DBManager.closePreparedStatement(insertBoardPstmt);
DBManager.closeResultSet(idresult);
DBManager.trueAutoCommit(conn);
}
if (firstsuccess == 1 && secondsuccess && thirdsuccess == 1) {
return "print Board \"" + boardName +"\" succesfully created.";
}
else if (firstsuccess == 0 && !sqlex) {
return "print Error: Cannot create a board with the name \"" + boardName
+ "\".";
}
else if (secondsuccess && !sqlex) {
return "print Error: Database error while creating/initializing a board database. Contact an admin.";
}
else if (!sqlex){
return "print Error: Could not add admin to the board db. Contact the admin.";
}
else {
return sqlexmsg;
}
}
}
|