Skip to content

Commit

Permalink
Added methods in LicenseActivation and DAOLicense + Tests
Browse files Browse the repository at this point in the history
  • Loading branch information
panuozzo77 committed Jan 2, 2024
1 parent a17ff4e commit 1159ba9
Show file tree
Hide file tree
Showing 9 changed files with 512 additions and 9 deletions.
104 changes: 104 additions & 0 deletions src/main/java/model/DAO/DAOLicense.java
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,108 @@ public void activate(License license, int userId) {
}
}
}

/**
* Generate a new License to sell
* @return the sequence of the License if operation succeed, none otherwise
*/
public String generateLicense(){
final int length = 8;
License l = new License(length);
String insertQuery = "INSERT INTO TalkAID2.license (Sequence, ID_User, ExpirationDate) VALUES (?, ?, ?);";
Connection connection = null;
PreparedStatement preparedStatement = null;

try {
connection = DAOConnection.getConnection();
preparedStatement = connection.prepareStatement(insertQuery);
preparedStatement.setString(1, l.getSequence());
preparedStatement.setInt(2, 0);
preparedStatement.setDate(3, null);
preparedStatement.executeUpdate();
return l.getSequence();
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
try {
if (preparedStatement != null) preparedStatement.close();
DAOConnection.releaseConnection(connection);
} catch (SQLException e) {
// Handle the exception (e.g., log or throw)
e.printStackTrace();
}
}
}


/**
* Generate an invitation code for a new patient
* @param userId the ID of a speech therapist
* @return the sequence of the invitation if operation succeed, none otherwise
*/
public String generateInvitation(int userId){
final int length = 4;
License l = new License(length);
String insertQuery = "INSERT INTO TalkAID2.license (Sequence, ID_User, ExpirationDate) VALUES (?,?,?);";
Connection connection = null;
PreparedStatement preparedStatement = null;

try {
connection = DAOConnection.getConnection();
preparedStatement = connection.prepareStatement(insertQuery);
preparedStatement.setString(1, l.getSequence());
preparedStatement.setInt(2, userId);
preparedStatement.setDate(3, l.getExpirationDate());
preparedStatement.executeUpdate();
return l.getSequence();
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
try {
if (preparedStatement != null) preparedStatement.close();
DAOConnection.releaseConnection(connection);
} catch (SQLException e) {
// Handle the exception (e.g., log or throw)
e.printStackTrace();
}
}
}

public boolean deleteLicense(String code) {
Connection connection = null;
PreparedStatement preparedStatement = null;

try {
// Get database connection
connection = DAOConnection.getConnection();

// Prepare the SQL query
String query = "DELETE FROM TalkAID2.license WHERE Sequence = ?";
preparedStatement = connection.prepareStatement(query);

// Set parameter for the prepared statement
preparedStatement.setString(1, code);

// Execute update and return boolean based on the affected rows
int rowsAffected = preparedStatement.executeUpdate();
return rowsAffected > 0;

} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close the statement and release the connection
try {
if (preparedStatement != null) preparedStatement.close();
DAOConnection.releaseConnection(connection);
} catch (SQLException e) {
e.printStackTrace();
}
}

// If exception occurs, return false
return false;
}

}
40 changes: 40 additions & 0 deletions src/main/java/model/DAO/DAOPersonalInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -96,5 +96,45 @@ public PersonalInfo getPersonalInfo(int id) {

return null; // Return null if personal_info does not exist
}

public boolean deleteRegistry(int createdUserId) {
Connection connection = null;
PreparedStatement preparedStatement = null;

try {
connection = DAOConnection.getConnection();
connection.setAutoCommit(false); // Start a transaction

String sql = "DELETE FROM personal_info WHERE ID_user = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, createdUserId);
int rowAffected = preparedStatement.executeUpdate();

connection.commit(); // Commit the transaction

return rowAffected > 0; // Return true if the deletion was successful

} catch (SQLException e) {
// Handle the exception (e.g., log or throw)
e.printStackTrace();
try {
if (connection != null) {
connection.rollback(); // Rollback the transaction in case of an exception
}
} catch (SQLException ex) {
ex.printStackTrace();
}
} finally {
try {
if (preparedStatement != null) preparedStatement.close();
DAOConnection.releaseConnection(connection);
} catch (SQLException e) {
// Handle the exception (e.g., log or throw)
e.printStackTrace();
}
}

return false; // Default to false if an exception occurs
}
}

43 changes: 43 additions & 0 deletions src/main/java/model/DAO/DAOUser.java
Original file line number Diff line number Diff line change
Expand Up @@ -331,4 +331,47 @@ public boolean updateEmailTime(String id, String value) {
// Default to false if an exception occurs
return false;
}

/**
* Deletes a user from the User table based on an ID or an email.
*
* @param idOrEmail Either an Integer representing the User's ID or a String representing the User's email.
* @return true if the user was successfully deleted; false otherwise.
*/
public boolean deleteUserByIdOrEmail(Object idOrEmail) {
Connection connection = null;
PreparedStatement preparedStatement = null;

try {
connection = DAOConnection.getConnection();
String query = null;

if (idOrEmail instanceof Integer) {
query = "DELETE FROM user WHERE ID = ?";
} else if (idOrEmail instanceof String) {
query = "DELETE FROM user WHERE Email = ?";
}

preparedStatement = connection.prepareStatement(query);
preparedStatement.setObject(1, idOrEmail);

int rowsDeleted = preparedStatement.executeUpdate();

return rowsDeleted > 0;
} catch (SQLException e) {
// Handle the exception (e.g., log or throw)
e.printStackTrace();
} finally {
try {
if (preparedStatement != null) preparedStatement.close();
DAOConnection.releaseConnection(connection);
} catch (SQLException e) {
// Handle the exception (e.g., log or throw)
e.printStackTrace();
}
}

// Default to false if an exception occurs
return false;
}
}
31 changes: 31 additions & 0 deletions src/main/java/model/entity/License.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
package model.entity;

import java.security.SecureRandom;
import java.sql.Date;
import java.time.LocalDate;

public class License {
private String sequence;
private int idUser;
private Date expirationDate;
private boolean active;

public License() {}
//Constructor for creating a pin or a license based on n
public License(int n){
this.sequence = generatePin(n);
if (n == 4){
LocalDate d = LocalDate.now();
d = d.plusDays(7);
this.expirationDate = java.sql.Date.valueOf(d);
}
}
// Getter and Setter methods

public String getSequence() {
Expand Down Expand Up @@ -41,4 +53,23 @@ public boolean isActive() {
public void setActive(boolean active) {
this.active = active;
}

private String generatePin(int n){
SecureRandom random = new SecureRandom();

String digits;

if(n==4){
digits = "0123456789";
}else{
digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}

StringBuilder pin = new StringBuilder();
for(int i = 0; i < n; i++) {
pin.append(digits.charAt(random.nextInt(digits.length())));
}

return pin.toString();
}
}
11 changes: 4 additions & 7 deletions src/main/java/model/service/license/LicenseActivation.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,11 @@ public void activate(License license, int userId) {
daoLicense.activate(license, userId);
}

public void generatePin(int therapistId) {
//TODO
// Implement the logic to generate a new license with a 4-character pin
// and associate it with the provided therapistId
public String generatePin(int therapistId) {
return daoLicense.generateInvitation(therapistId);
}

public void generateLicense() {
//TODO
// Implement the logic to generate a new license with 8 characters and therapistId 0
public String generateLicense() {
return daoLicense.generateLicense();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ public interface LicenseActivationInterface {
*
* @param therapistId è l'identificativo del terapeuta
*/
void generatePin(int therapistId);
String generatePin(int therapistId);

/**
* genera una nuova licenza da 8 caratteri e con ID terapeuta 0
*/
void generateLicense();
String generateLicense();

}
98 changes: 98 additions & 0 deletions src/test/java/model/DAO/DAOLicenseTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package model.DAO;

import model.entity.License;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.sql.SQLException;

import static org.junit.jupiter.api.Assertions.*;

class DAOLicenseTest {

private DAOLicense daoLicense;
private String generatedLicense;
private String generatedInvitation;

@BeforeEach
void setup() {
daoLicense = new DAOLicense();
}

@Test
void testGetLicenseByCode() {
// Mock the license code
String code = "0D47AB8F";

// Call the method to test
License license = daoLicense.getLicenseByCode(code);

// Check the returned license
assertNotNull(license, "License should not be null");
assertEquals(code, license.getSequence(), "Sequence should match");
// Add more assertions based on your specific requirements
}

@Test
void testGenerateLicense() {
// Call the method to generate a license
generatedLicense = daoLicense.generateLicense();

// Check if the generated license sequence is not null
assertNotNull(generatedLicense, "Generated license sequence should not be null");
assertEquals(8, generatedLicense.length(), "Generated license sequence should have the specified length");

boolean result1 = daoLicense.deleteLicense(generatedLicense);
assertTrue(result1, "The license should be deleted");

boolean result3 = daoLicense.deleteLicense(generatedLicense);
assertFalse(result3, "The license can't be deleted");
}

@Test
void testGenerateInvitation() {
// Mock therapist ID
int therapistId = 123;

// Call the method to generate an invitation
generatedInvitation = daoLicense.generateInvitation(therapistId);

// Check if the generated invitation sequence is not null
assertNotNull(generatedInvitation, "Generated invitation sequence should not be null");
assertEquals(4, generatedInvitation.length(), "Generated invitation sequence should have the specified length");
// Additional assertions if needed

boolean result2 = daoLicense.deleteLicense(generatedInvitation);
assertTrue(result2, "The invitation should be deleted");


boolean result4 = daoLicense.deleteLicense(generatedInvitation);
assertFalse(result4, "The invitation can't be deleted");
}


@Test
void testActivateLicense() {
// Mock the license and user ID
License license = new License();
license.setSequence("BDC3");
license.setIdUser(4);
license.setExpirationDate(java.sql.Date.valueOf("2024-06-27"));
license.setActive(true);

int userId = 4;

// Call the method to test
daoLicense.activate(license, userId);

// After activation, let's retrieve the updated license
License updatedLicense = daoLicense.getLicenseByCode(license.getSequence());

// Check the updated license
assertNotNull(updatedLicense, "Updated license should not be null");
assertEquals(userId, updatedLicense.getIdUser(), "User ID should be updated");
assertTrue(updatedLicense.isActive(), "License should be activated");
// Add more assertions based on your specific requirements
}
}

Loading

0 comments on commit 1159ba9

Please sign in to comment.