diff --git a/pom.xml b/pom.xml
index 479eee01..0b9f762b 100644
--- a/pom.xml
+++ b/pom.xml
@@ -159,7 +159,6 @@
maven-javadoc-plugin
private
-
diff --git a/ukelonn.backend/src/main/java/no/priv/bang/ukelonn/backend/UkelonnServiceProvider.java b/ukelonn.backend/src/main/java/no/priv/bang/ukelonn/backend/UkelonnServiceProvider.java
index 6bee23c9..d430534f 100644
--- a/ukelonn.backend/src/main/java/no/priv/bang/ukelonn/backend/UkelonnServiceProvider.java
+++ b/ukelonn.backend/src/main/java/no/priv/bang/ukelonn/backend/UkelonnServiceProvider.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016-2021 Steinar Bang
+ * Copyright 2016-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,9 +22,7 @@
import org.osgi.service.log.Logger;
import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
import java.nio.charset.StandardCharsets;
-import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@@ -33,9 +31,7 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
-import java.util.Enumeration;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -121,13 +117,13 @@ public LogService getLogservice() {
@Override
public List getAccounts() {
- List accounts = new ArrayList<>();
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("select * from accounts_view")) {
- try(ResultSet results = statement.executeQuery()) {
+ var accounts = new ArrayList();
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("select * from accounts_view")) {
+ try(var results = statement.executeQuery()) {
if (results != null) {
while(results.next()) {
- Account newaccount = mapAccount(results);
+ var newaccount = mapAccount(results);
accounts.add(newaccount);
}
}
@@ -143,10 +139,10 @@ public List getAccounts() {
@Override
public Account getAccount(String username) {
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("select * from accounts_view where username=?")) {
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("select * from accounts_view where username=?")) {
statement.setString(1, username);
- try(ResultSet resultset = statement.executeQuery()) {
+ try(var resultset = statement.executeQuery()) {
if (resultset.next())
{
return mapAccount(resultset);
@@ -163,12 +159,12 @@ public Account getAccount(String username) {
@Override
public Account registerPerformedJob(PerformedTransaction job) {
- int accountId = job.getAccount().getAccountId();
- int jobtypeId = job.getTransactionTypeId();
- double jobamount = addBonus(job.getTransactionAmount());
- Date timeofjob = job.getTransactionDate();
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("insert into transactions (account_id, transaction_type_id,transaction_amount, transaction_time) values (?, ?, ?, ?)")) {
+ var accountId = job.account().accountId();
+ var jobtypeId = job.transactionTypeId();
+ var jobamount = addBonus(job.transactionAmount());
+ var timeofjob = job.transactionDate();
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("insert into transactions (account_id, transaction_type_id,transaction_amount, transaction_time) values (?, ?, ?, ?)")) {
statement.setInt(1, accountId);
statement.setInt(2, jobtypeId);
statement.setDouble(3, jobamount);
@@ -176,22 +172,22 @@ public Account registerPerformedJob(PerformedTransaction job) {
statement.executeUpdate();
}
} catch (SQLException exception) {
- String message = String.format("Failed to register performed job in the database, account: %d jobtype: %d amount: %f", accountId, jobtypeId, jobamount);
+ var message = String.format("Failed to register performed job in the database, account: %d jobtype: %d amount: %f", accountId, jobtypeId, jobamount);
logError(message, exception);
}
- return getAccount(job.getAccount().getUsername());
+ return getAccount(job.account().username());
}
@Override
public List getJobTypes() {
- List jobtypes = new ArrayList<>();
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("select * from transaction_types where transaction_is_work=true")) {
- try(ResultSet resultSet = statement.executeQuery()) {
+ var jobtypes = new ArrayList();
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("select * from transaction_types where transaction_is_work=true")) {
+ try(var resultSet = statement.executeQuery()) {
if (resultSet != null) {
while (resultSet.next()) {
- TransactionType transactiontype = UkelonnServiceProvider.mapTransactionType(resultSet);
+ var transactiontype = UkelonnServiceProvider.mapTransactionType(resultSet);
jobtypes.add(transactiontype);
}
}
@@ -211,7 +207,7 @@ public List getJobs(int accountId) {
@Override
public List getPayments(int accountId) {
- List payments = getTransactionsFromAccount(accountId, "/sql/query/payments_last_n.sql", "payments");
+ var payments = getTransactionsFromAccount(accountId, "/sql/query/payments_last_n.sql", "payments");
payments = UkelonnServiceProvider.makePaymentAmountsPositive(payments); // Payments are negative numbers in the DB, presented as positive numbers in the GUI
return payments;
}
@@ -220,13 +216,13 @@ List getTransactionsFromAccount(int accountId,
String sqlTemplate,
String transactionType)
{
- List transactions = new ArrayList<>();
- String sql = String.format(getResourceAsString(sqlTemplate), UkelonnServiceProvider.NUMBER_OF_TRANSACTIONS_TO_DISPLAY);
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement(sql)) {
+ var transactions = new ArrayList();
+ var sql = String.format(getResourceAsString(sqlTemplate), UkelonnServiceProvider.NUMBER_OF_TRANSACTIONS_TO_DISPLAY);
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement(sql)) {
statement.setInt(1, accountId);
trySettingPreparedStatementParameterThatMayNotBePresent(statement, 2, accountId);
- try(ResultSet resultSet = statement.executeQuery()) {
+ try(var resultSet = statement.executeQuery()) {
while (resultSet.next()) {
transactions.add(UkelonnServiceProvider.mapTransaction(resultSet));
}
@@ -242,9 +238,9 @@ List getTransactionsFromAccount(int accountId,
@Override
public List deleteJobsFromAccount(int accountId, List idsOfJobsToDelete) {
if (!idsOfJobsToDelete.isEmpty()) {
- String deleteQuery = "delete from transactions where transaction_id in (select transaction_id from transactions inner join transaction_types on transactions.transaction_type_id=transaction_types.transaction_type_id where transaction_id in (" + joinIds(idsOfJobsToDelete) + ") and transaction_types.transaction_is_work=? and account_id=?)";
- try(Connection connection = datasource.getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(deleteQuery)) { // NOSONAR This string manipulation is OK and the only way to do it
+ var deleteQuery = "delete from transactions where transaction_id in (select transaction_id from transactions inner join transaction_types on transactions.transaction_type_id=transaction_types.transaction_type_id where transaction_id in (" + joinIds(idsOfJobsToDelete) + ") and transaction_types.transaction_is_work=? and account_id=?)";
+ try(var connection = datasource.getConnection()) {
+ try (var statement = connection.prepareStatement(deleteQuery)) { // NOSONAR This string manipulation is OK and the only way to do it
addParametersToDeleteJobsStatement(accountId, statement);
statement.executeUpdate();
}
@@ -270,31 +266,31 @@ void addParametersToDeleteJobsStatement(int accountId, PreparedStatement stateme
@Override
public List updateJob(UpdatedTransaction editedJob) {
- String sql = "update transactions set transaction_type_id=?, transaction_time=?, transaction_amount=? where transaction_id=?";
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement(sql)) {
- statement.setInt(1, editedJob.getTransactionTypeId());
- statement.setTimestamp(2, new java.sql.Timestamp(editedJob.getTransactionTime().getTime()));
- statement.setDouble(3, editedJob.getTransactionAmount());
- statement.setInt(4, editedJob.getId());
+ var sql = "update transactions set transaction_type_id=?, transaction_time=?, transaction_amount=? where transaction_id=?";
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement(sql)) {
+ statement.setInt(1, editedJob.transactionTypeId());
+ statement.setTimestamp(2, new java.sql.Timestamp(editedJob.transactionTime().getTime()));
+ statement.setDouble(3, editedJob.transactionAmount());
+ statement.setInt(4, editedJob.id());
statement.executeUpdate();
}
} catch (SQLException e) {
- throw new UkelonnException(String.format("Failed to update job with id %d", editedJob.getId()) , e);
+ throw new UkelonnException(String.format("Failed to update job with id %d", editedJob.id()) , e);
}
- return getJobs(editedJob.getAccountId());
+ return getJobs(editedJob.accountId());
}
@Override
public List getPaymenttypes() {
- List paymenttypes = new ArrayList<>();
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("select * from transaction_types where transaction_is_wage_payment=true")) {
- try(ResultSet resultSet = statement.executeQuery()) {
+ var paymenttypes = new ArrayList();
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("select * from transaction_types where transaction_is_wage_payment=true")) {
+ try(var resultSet = statement.executeQuery()) {
if (resultSet != null) {
while (resultSet.next()) {
- TransactionType transactiontype = UkelonnServiceProvider.mapTransactionType(resultSet);
+ var transactiontype = UkelonnServiceProvider.mapTransactionType(resultSet);
paymenttypes.add(transactiontype);
}
}
@@ -309,12 +305,12 @@ public List getPaymenttypes() {
@Override
public Account registerPayment(PerformedTransaction payment) {
- int accountId = payment.getAccount().getAccountId();
- int transactionTypeId = payment.getTransactionTypeId();
- double amount = 0 - payment.getTransactionAmount();
- Date transactionDate = new Date();
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("insert into transactions (account_id,transaction_type_id,transaction_amount, transaction_time) values (?, ?, ?, ?)")) {
+ var accountId = payment.account().accountId();
+ var transactionTypeId = payment.transactionTypeId();
+ var amount = 0 - payment.transactionAmount();
+ var transactionDate = new Date();
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("insert into transactions (account_id,transaction_type_id,transaction_amount, transaction_time) values (?, ?, ?, ?)")) {
statement.setInt(1, accountId);
statement.setInt(2, transactionTypeId);
statement.setDouble(3, amount);
@@ -322,25 +318,25 @@ public Account registerPayment(PerformedTransaction payment) {
statement.executeUpdate();
}
} catch (SQLException e) {
- String message = String.format("Failed to register payment accountId: %d transactionTypeId: %d amount: %f", accountId, transactionTypeId, amount);
+ var message = String.format("Failed to register payment accountId: %d transactionTypeId: %d amount: %f", accountId, transactionTypeId, amount);
logError(message, e);
return null;
}
- return getAccount(payment.getAccount().getUsername());
+ return getAccount(payment.account().username());
}
@Override
public List modifyJobtype(TransactionType jobtype) {
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("update transaction_types set transaction_type_name=?, transaction_amount=?, transaction_is_work=true, transaction_is_wage_payment=false where transaction_type_id=?")) {
- statement.setString(1, jobtype.getTransactionTypeName());
- statement.setDouble(2, jobtype.getTransactionAmount());
- statement.setInt(3, jobtype.getId());
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("update transaction_types set transaction_type_name=?, transaction_amount=?, transaction_is_work=true, transaction_is_wage_payment=false where transaction_type_id=?")) {
+ statement.setString(1, jobtype.transactionTypeName());
+ statement.setDouble(2, jobtype.transactionAmount());
+ statement.setInt(3, jobtype.id());
statement.executeUpdate();
}
} catch (SQLException e) {
- String message = String.format("Failed to update jobtype %d in the database", jobtype.getId());
+ var message = String.format("Failed to update jobtype %d in the database", jobtype.id());
logError(message, e);
throw new UkelonnException(message, e);
}
@@ -350,14 +346,14 @@ public List modifyJobtype(TransactionType jobtype) {
@Override
public List createJobtype(TransactionType jobtype) {
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("insert into transaction_types (transaction_type_name, transaction_amount, transaction_is_work, transaction_is_wage_payment) values (?, ?, true, false)")) {
- statement.setString(1, jobtype.getTransactionTypeName());
- statement.setObject(2, jobtype.getTransactionAmount());
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("insert into transaction_types (transaction_type_name, transaction_amount, transaction_is_work, transaction_is_wage_payment) values (?, ?, true, false)")) {
+ statement.setString(1, jobtype.transactionTypeName());
+ statement.setObject(2, jobtype.transactionAmount());
statement.executeUpdate();
}
} catch (SQLException e) {
- String message = String.format("Failed to create jobtype \"%s\" in the database", jobtype.getTransactionTypeName());
+ var message = String.format("Failed to create jobtype \"%s\" in the database", jobtype.transactionTypeName());
logError(message, e);
throw new UkelonnException(message, e);
}
@@ -367,15 +363,15 @@ public List createJobtype(TransactionType jobtype) {
@Override
public List modifyPaymenttype(TransactionType paymenttype) {
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("update transaction_types set transaction_type_name=?, transaction_amount=?, transaction_is_work=false, transaction_is_wage_payment=true where transaction_type_id=?")) {
- statement.setString(1, paymenttype.getTransactionTypeName());
- statement.setDouble(2, paymenttype.getTransactionAmount());
- statement.setInt(3, paymenttype.getId());
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("update transaction_types set transaction_type_name=?, transaction_amount=?, transaction_is_work=false, transaction_is_wage_payment=true where transaction_type_id=?")) {
+ statement.setString(1, paymenttype.transactionTypeName());
+ statement.setDouble(2, paymenttype.transactionAmount());
+ statement.setInt(3, paymenttype.id());
statement.executeUpdate();
}
} catch (SQLException e) {
- String message = String.format("Failed to update payment type %d in the database", paymenttype.getId());
+ var message = String.format("Failed to update payment type %d in the database", paymenttype.id());
logError(message, e);
throw new UkelonnException(message, e);
}
@@ -385,14 +381,14 @@ public List modifyPaymenttype(TransactionType paymenttype) {
@Override
public List createPaymenttype(TransactionType paymenttype) {
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("insert into transaction_types (transaction_type_name, transaction_amount, transaction_is_work, transaction_is_wage_payment) values (?, ?, false, true)")) {
- statement.setString(1, paymenttype.getTransactionTypeName());
- statement.setObject(2, paymenttype.getTransactionAmount());
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("insert into transaction_types (transaction_type_name, transaction_amount, transaction_is_work, transaction_is_wage_payment) values (?, ?, false, true)")) {
+ statement.setString(1, paymenttype.transactionTypeName());
+ statement.setObject(2, paymenttype.transactionAmount());
statement.executeUpdate();
}
} catch (SQLException e) {
- String message = String.format("Failed to create payment type \"%s\" in the database", paymenttype.getTransactionTypeName());
+ var message = String.format("Failed to create payment type \"%s\" in the database", paymenttype.transactionTypeName());
logError(message, e);
throw new UkelonnException(message, e);
}
@@ -402,18 +398,18 @@ public List createPaymenttype(TransactionType paymenttype) {
@Override
public Account addAccount(User user) {
- String username = user.getUsername();
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement insertAccountSql = connection.prepareStatement("insert into accounts (username) values (?)")) {
+ var username = user.username();
+ try(var connection = datasource.getConnection()) {
+ try(var insertAccountSql = connection.prepareStatement("insert into accounts (username) values (?)")) {
insertAccountSql.setString(1, username);
insertAccountSql.executeUpdate();
}
addDummyPaymentToAccountSoThatAccountWillAppearInAccountsView(username);
- return getAccount(user.getUsername());
+ return getAccount(user.username());
} catch (SQLException e) {
- String message = "Database exception when account for new user";
+ var message = "Database exception when account for new user";
logger.error(message, e);
throw new UkelonnException(message, e);
}
@@ -421,13 +417,13 @@ public Account addAccount(User user) {
@Override
public List earningsSumOverYear(String username) {
- List statistics = new ArrayList<>();
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("select aggregate_amount, aggregate_year from sum_over_year_view where username=?")) {
+ var statistics = new ArrayList();
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("select aggregate_amount, aggregate_year from sum_over_year_view where username=?")) {
statement.setString(1, username);
- try(ResultSet resultSet = statement.executeQuery()) {
+ try(var resultSet = statement.executeQuery()) {
while (resultSet.next()) {
- SumYear sumYear = SumYear.with()
+ var sumYear = SumYear.with()
.sum(resultSet.getDouble(1))
.year(resultSet.getInt(2))
.build();
@@ -444,13 +440,13 @@ public List earningsSumOverYear(String username) {
@Override
public List earningsSumOverMonth(String username) {
- List statistics = new ArrayList<>();
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("select aggregate_amount, aggregate_year, aggregate_month from sum_over_year_and_month_view where username=?")) {
+ var statistics = new ArrayList();
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("select aggregate_amount, aggregate_year, aggregate_month from sum_over_year_and_month_view where username=?")) {
statement.setString(1, username);
- try(ResultSet resultSet = statement.executeQuery()) {
+ try(var resultSet = statement.executeQuery()) {
while (resultSet.next()) {
- SumYearMonth sumYearMonth = SumYearMonth.with()
+ var sumYearMonth = SumYearMonth.with()
.sum(resultSet.getDouble(1))
.year(resultSet.getInt(2))
.month(resultSet.getInt(3))
@@ -468,8 +464,8 @@ public List earningsSumOverMonth(String username) {
@Override
public List notificationsTo(String username) {
- ConcurrentLinkedQueue notifications = getNotificationQueueForUser(username);
- Notification notification = notifications.poll();
+ var notifications = getNotificationQueueForUser(username);
+ var notification = notifications.poll();
if (notification == null) {
return Collections.emptyList();
}
@@ -479,19 +475,19 @@ public List notificationsTo(String username) {
@Override
public void notificationTo(String username, Notification notification) {
- ConcurrentLinkedQueue notifications = getNotificationQueueForUser(username);
+ var notifications = getNotificationQueueForUser(username);
notifications.add(notification);
}
@Override
public List getActiveBonuses() {
- List activebonuses = new ArrayList<>();
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("select * from bonuses where enabled and start_date <= ? and end_date >= ?")) {
- Timestamp today = Timestamp.from(new Date().toInstant());
+ var activebonuses = new ArrayList();
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("select * from bonuses where enabled and start_date <= ? and end_date >= ?")) {
+ var today = Timestamp.from(new Date().toInstant());
statement.setTimestamp(1, today);
statement.setTimestamp(2, today);
- try (ResultSet results = statement.executeQuery()) {
+ try (var results = statement.executeQuery()) {
while (results.next()) {
buildBonusFromResultSetAndAddToList(activebonuses, results);
}
@@ -506,10 +502,10 @@ public List getActiveBonuses() {
@Override
public List getAllBonuses() {
- List allbonuses = new ArrayList<>();
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("select * from bonuses")) {
- try (ResultSet results = statement.executeQuery()) {
+ var allbonuses = new ArrayList();
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("select * from bonuses")) {
+ try (var results = statement.executeQuery()) {
while (results.next()) {
buildBonusFromResultSetAndAddToList(allbonuses, results);
}
@@ -524,17 +520,17 @@ public List getAllBonuses() {
@Override
public List createBonus(Bonus newBonus) {
- String title = newBonus.getTitle();
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("insert into bonuses (enabled, iconurl, title, description, bonus_factor, start_date, end_date) values (?, ?, ?, ?, ?, ?, ?)")) {
- statement.setBoolean(1, newBonus.isEnabled());
- statement.setString(2, newBonus.getIconurl());
+ var title = newBonus.title();
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("insert into bonuses (enabled, iconurl, title, description, bonus_factor, start_date, end_date) values (?, ?, ?, ?, ?, ?, ?)")) {
+ statement.setBoolean(1, newBonus.enabled());
+ statement.setString(2, newBonus.iconurl());
statement.setString(3, title);
- statement.setString(4, newBonus.getDescription());
- statement.setDouble(5, newBonus.getBonusFactor());
- Date startDate = newBonus.getStartDate() != null ? newBonus.getStartDate() : new Date();
+ statement.setString(4, newBonus.description());
+ statement.setDouble(5, newBonus.bonusFactor());
+ var startDate = newBonus.startDate() != null ? newBonus.startDate() : new Date();
statement.setTimestamp(6, Timestamp.from(startDate.toInstant()));
- Date endDate = newBonus.getEndDate() != null ? newBonus.getEndDate() : new Date();
+ var endDate = newBonus.endDate() != null ? newBonus.endDate() : new Date();
statement.setTimestamp(7, Timestamp.from(endDate.toInstant()));
statement.executeUpdate();
}
@@ -547,16 +543,16 @@ public List createBonus(Bonus newBonus) {
@Override
public List modifyBonus(Bonus updatedBonus) {
- int id = updatedBonus.getBonusId();
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("update bonuses set enabled=?, iconurl=?, title=?, description=?, bonus_factor=?, start_date=?, end_date=? where bonus_id=?")) {
- statement.setBoolean(1, updatedBonus.isEnabled());
- statement.setString(2, updatedBonus.getIconurl());
- statement.setString(3, updatedBonus.getTitle());
- statement.setString(4, updatedBonus.getDescription());
- statement.setDouble(5, updatedBonus.getBonusFactor());
- statement.setTimestamp(6, Timestamp.from(updatedBonus.getStartDate().toInstant()));
- statement.setTimestamp(7, Timestamp.from(updatedBonus.getEndDate().toInstant()));
+ var id = updatedBonus.bonusId();
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("update bonuses set enabled=?, iconurl=?, title=?, description=?, bonus_factor=?, start_date=?, end_date=? where bonus_id=?")) {
+ statement.setBoolean(1, updatedBonus.enabled());
+ statement.setString(2, updatedBonus.iconurl());
+ statement.setString(3, updatedBonus.title());
+ statement.setString(4, updatedBonus.description());
+ statement.setDouble(5, updatedBonus.bonusFactor());
+ statement.setTimestamp(6, Timestamp.from(updatedBonus.startDate().toInstant()));
+ statement.setTimestamp(7, Timestamp.from(updatedBonus.endDate().toInstant()));
statement.setInt(8, id);
statement.executeUpdate();
}
@@ -569,9 +565,9 @@ public List modifyBonus(Bonus updatedBonus) {
@Override
public List deleteBonus(Bonus removedBonus) {
- int id = removedBonus.getBonusId();
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement("delete from bonuses where bonus_id=?")) {
+ var id = removedBonus.bonusId();
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement("delete from bonuses where bonus_id=?")) {
statement.setInt(1, id);
statement.executeUpdate();
}
@@ -602,17 +598,17 @@ private ConcurrentLinkedQueue getNotificationQueueForUser(String u
}
double addBonus(double transactionAmount) {
- List activebonuses = getActiveBonuses();
+ var activebonuses = getActiveBonuses();
if (activebonuses.isEmpty()) {
return transactionAmount;
}
- double bonus = activebonuses.stream().mapToDouble(b -> b.getBonusFactor() * transactionAmount - transactionAmount).sum();
+ var bonus = activebonuses.stream().mapToDouble(b -> b.bonusFactor() * transactionAmount - transactionAmount).sum();
return transactionAmount + bonus;
}
void buildBonusFromResultSetAndAddToList(List allbonuses, ResultSet results) throws SQLException {
- Bonus bonus = Bonus.with()
+ var bonus = Bonus.with()
.bonusId(results.getInt("bonus_id"))
.enabled(results.getBoolean("enabled"))
.iconurl(results.getString("iconurl"))
@@ -626,20 +622,20 @@ void buildBonusFromResultSetAndAddToList(List allbonuses, ResultSet resul
}
static boolean passwordsEqualsAndNotEmpty(PasswordsWithUser passwords) {
- if (passwords.getPassword() == null || passwords.getPassword().isEmpty()) {
+ if (passwords.password() == null || passwords.password().isEmpty()) {
return false;
}
- return passwords.getPassword().equals(passwords.getPassword2());
+ return passwords.password().equals(passwords.password2());
}
static StringBuilder joinIds(List ids) {
- StringBuilder commaList = new StringBuilder();
+ var commaList = new StringBuilder();
if (ids == null) {
return commaList;
}
- Iterator iterator = ids.iterator();
+ var iterator = ids.iterator();
if (!iterator.hasNext()) {
return commaList; // Return an empty string builder instead of a null
}
@@ -653,12 +649,12 @@ static StringBuilder joinIds(List ids) {
}
static boolean hasUserWithNonEmptyUsername(PasswordsWithUser passwords) {
- User user = passwords.getUser();
+ var user = passwords.user();
if (user == null) {
return false;
}
- String username = user.getUsername();
+ var username = user.username();
if (username == null) {
return false;
}
@@ -692,8 +688,8 @@ private void logWarning(String message, Exception e) {
* @return the update status
*/
int addDummyPaymentToAccountSoThatAccountWillAppearInAccountsView(String username) {
- try(Connection connection = datasource.getConnection()) {
- try(PreparedStatement statement = connection.prepareStatement(getResourceAsString("/sql/query/insert_empty_payment_in_account_keyed_by_username.sql"))) {
+ try(var connection = datasource.getConnection()) {
+ try(var statement = connection.prepareStatement(getResourceAsString("/sql/query/insert_empty_payment_in_account_keyed_by_username.sql"))) {
statement.setString(1, username);
return statement.executeUpdate();
}
@@ -705,10 +701,10 @@ int addDummyPaymentToAccountSoThatAccountWillAppearInAccountsView(String usernam
}
String getResourceAsString(String resourceName) {
- ByteArrayOutputStream resource = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
+ var resource = new ByteArrayOutputStream();
+ var buffer = new byte[1024];
int length;
- try(InputStream resourceStream = getClass().getResourceAsStream(resourceName)) {
+ try(var resourceStream = getClass().getResourceAsStream(resourceName)) {
while ((length = resourceStream.read(buffer)) != -1) {
resource.write(buffer, 0, length);
}
@@ -722,9 +718,9 @@ String getResourceAsString(String resourceName) {
}
public Account mapAccount(ResultSet results) throws SQLException {
- String username = results.getString(UkelonnServiceProvider.USERNAME);
+ var username = results.getString(UkelonnServiceProvider.USERNAME);
try {
- no.priv.bang.osgiservice.users.User user = useradmin.getUser(username);
+ var user = useradmin.getUser(username);
return Account.with()
.accountid(results.getInt("account_id"))
.username(username)
@@ -743,14 +739,14 @@ public Account mapAccount(ResultSet results) throws SQLException {
}
private void addRolesIfNotPresent() {
- Optional ukelonnadmin = addRoleIfNotPresent(UKELONNADMIN_ROLE, "Administrator av applikasjonen ukelonn");
+ var ukelonnadmin = addRoleIfNotPresent(UKELONNADMIN_ROLE, "Administrator av applikasjonen ukelonn");
addRoleIfNotPresent(UKELONNUSER_ROLE, "Bruker av applikasjonen ukelonn");
addAdminroleToUserAdmin(ukelonnadmin);
}
Optional addRoleIfNotPresent(String rolename, String description) {
- List roles = useradmin.getRoles();
- Optional existingRole = roles.stream().filter(r -> rolename.equals(r.getRolename())).findFirst();
+ var roles = useradmin.getRoles();
+ var existingRole = roles.stream().filter(r -> rolename.equals(r.getRolename())).findFirst();
if (!existingRole.isPresent()) {
roles = useradmin.addRole(Role.with().rolename(rolename).description(description).build());
return roles.stream().filter(r -> rolename.equals(r.getRolename())).findFirst();
@@ -762,8 +758,8 @@ Optional addRoleIfNotPresent(String rolename, String description) {
void addAdminroleToUserAdmin(Optional ukelonnadmin) {
if (ukelonnadmin.isPresent()) {
try {
- no.priv.bang.osgiservice.users.User admin = useradmin.getUser("admin");
- List roles = useradmin.getRolesForUser("admin");
+ var admin = useradmin.getUser("admin");
+ var roles = useradmin.getRolesForUser("admin");
if (roles.stream().noneMatch(r -> ukelonnadmin.get().equals(r))) {
useradmin.addUserRoles(UserRoles.with().user(admin).roles(Arrays.asList(ukelonnadmin.get())).build());
}
@@ -784,9 +780,9 @@ static Transaction mapTransaction(ResultSet resultset) throws SQLException {
}
static List makePaymentAmountsPositive(List payments) {
- List paymentsWithPositiveAmounts = new ArrayList<>(payments.size());
- for (Transaction payment : payments) {
- double amount = Math.abs(payment.getTransactionAmount());
+ var paymentsWithPositiveAmounts = new ArrayList(payments.size());
+ for (var payment : payments) {
+ var amount = Math.abs(payment.transactionAmount());
paymentsWithPositiveAmounts.add(Transaction.with(payment).transactionAmount(amount).build());
}
@@ -804,9 +800,9 @@ static TransactionType mapTransactionType(ResultSet resultset) throws SQLExcepti
}
Map transformResourceBundleToMap(Locale locale) {
- Map map = new HashMap<>();
- ResourceBundle bundle = ResourceBundle.getBundle(RESOURCES_BASENAME, locale);
- Enumeration keys = bundle.getKeys();
+ var map = new HashMap();
+ var bundle = ResourceBundle.getBundle(RESOURCES_BASENAME, locale);
+ var keys = bundle.getKeys();
while(keys.hasMoreElements()) {
String key = keys.nextElement();
map.put(key, bundle.getString(key));
diff --git a/ukelonn.backend/src/test/java/no/priv/bang/ukelonn/backend/UkelonnServiceProviderTest.java b/ukelonn.backend/src/test/java/no/priv/bang/ukelonn/backend/UkelonnServiceProviderTest.java
index 1526feb2..672ca06b 100644
--- a/ukelonn.backend/src/test/java/no/priv/bang/ukelonn/backend/UkelonnServiceProviderTest.java
+++ b/ukelonn.backend/src/test/java/no/priv/bang/ukelonn/backend/UkelonnServiceProviderTest.java
@@ -193,12 +193,12 @@ void testGetAccount() {
when(useradmin.getUser(anyString())).thenReturn(user);
provider.setUserAdmin(useradmin);
var account = provider.getAccount("jad");
- assertEquals("jad", account.getUsername());
- assertEquals("Jane", account.getFirstName());
- assertEquals("Doe", account.getLastName());
- var jobs = provider.getJobs(account.getAccountId());
+ assertEquals("jad", account.username());
+ assertEquals("Jane", account.firstName());
+ assertEquals("Doe", account.lastName());
+ var jobs = provider.getJobs(account.accountId());
assertEquals(10, jobs.size());
- var payments = provider.getPayments(account.getAccountId());
+ var payments = provider.getPayments(account.accountId());
assertEquals(10, payments.size());
}
@@ -296,8 +296,8 @@ void testAddAccount() {
.lastname(newLastname)
.build();
var newAccount = ukelonn.addAccount(userWithUserId);
- assertThat(newAccount.getAccountId()).isPositive();
- assertEquals(0.0, newAccount.getBalance(), 0);
+ assertThat(newAccount.accountId()).isPositive();
+ assertEquals(0.0, newAccount.balance(), 0);
}
@Test
@@ -361,7 +361,7 @@ void testGetJobs() {
when(useradmin.getUser(anyString())).thenReturn(user);
ukelonn.setUserAdmin(useradmin);
var account = ukelonn.getAccount(username);
- var jobs = ukelonn.getJobs(account.getAccountId());
+ var jobs = ukelonn.getJobs(account.accountId());
assertEquals(10, jobs.size());
}
@@ -381,16 +381,16 @@ void testRegisterPerformedJob() throws Exception {
when(useradmin.getUser(anyString())).thenReturn(user);
ukelonn.setUserAdmin(useradmin);
var account = ukelonn.getAccount(username);
- var oldBalance = account.getBalance();
+ var oldBalance = account.balance();
var jobtype = ukelonn.getJobTypes().get(0);
var performedJob = PerformedTransaction.with()
.account(account)
- .transactionTypeId(jobtype.getId())
- .transactionAmount(jobtype.getTransactionAmount())
+ .transactionTypeId(jobtype.id())
+ .transactionAmount(jobtype.transactionAmount())
.transactionDate(new Date())
.build();
var updatedAccount = ukelonn.registerPerformedJob(performedJob);
- assertThat(updatedAccount.getBalance()).isGreaterThan(oldBalance);
+ assertThat(updatedAccount.balance()).isGreaterThan(oldBalance);
} finally {
restoreTestDatabase();
}
@@ -462,12 +462,12 @@ void testDeleteAllJobsOfUser() throws Exception {
when(useradmin.getUser(anyString())).thenReturn(user);
ukelonn.setUserAdmin(useradmin);
var account = ukelonn.getAccount(username);
- var jobs = ukelonn.getJobs(account.getAccountId());
+ var jobs = ukelonn.getJobs(account.accountId());
assertEquals(2, jobs.size());
- var idsOfJobsToDelete = Arrays.asList(jobs.get(0).getId(), jobs.get(1).getId());
+ var idsOfJobsToDelete = Arrays.asList(jobs.get(0).id(), jobs.get(1).id());
// Do the delete
- var jobsAfterDelete = ukelonn.deleteJobsFromAccount(account.getAccountId(), idsOfJobsToDelete);
+ var jobsAfterDelete = ukelonn.deleteJobsFromAccount(account.accountId(), idsOfJobsToDelete);
// Check that the job list that was two items earlier is now empty
assertEquals(0, jobsAfterDelete.size());
@@ -493,12 +493,12 @@ void testDeleteSomeJobsOfUser() throws Exception {
when(useradmin.getUser(anyString())).thenReturn(user);
ukelonn.setUserAdmin(useradmin);
var account = ukelonn.getAccount(username);
- var jobs = ukelonn.getJobs(account.getAccountId());
+ var jobs = ukelonn.getJobs(account.accountId());
assertEquals(2, jobs.size());
- var idsOfJobsToDelete = Arrays.asList(jobs.get(0).getId());
+ var idsOfJobsToDelete = Arrays.asList(jobs.get(0).id());
// Do the delete
- var jobsAfterDelete = ukelonn.deleteJobsFromAccount(account.getAccountId(), idsOfJobsToDelete);
+ var jobsAfterDelete = ukelonn.deleteJobsFromAccount(account.accountId(), idsOfJobsToDelete);
// Check that the job list that was two items earlier is now empty
assertEquals(1, jobsAfterDelete.size());
@@ -548,12 +548,12 @@ void verifyDeletingNoJobsOfUserHasNoEffect() throws Exception {
var account = ukelonn.getAccount(username);
// Check preconditions
- var jobs = ukelonn.getJobs(account.getAccountId());
+ var jobs = ukelonn.getJobs(account.accountId());
assertEquals(2, jobs.size());
// Delete with an empty argument
List idsOfJobsToDelete = Collections.emptyList();
- var jobsAfterDelete = ukelonn.deleteJobsFromAccount(account.getAccountId(), idsOfJobsToDelete);
+ var jobsAfterDelete = ukelonn.deleteJobsFromAccount(account.accountId(), idsOfJobsToDelete);
// Verify that nothing has been deleted
assertEquals(2, jobsAfterDelete.size());
@@ -580,18 +580,18 @@ void verifyThatTryingToDeletePaymentsAsJobsWillDoNothing() throws Exception {
var account = ukelonn.getAccount(username);
// Check the preconditions
- var jobs = ukelonn.getJobs(account.getAccountId());
+ var jobs = ukelonn.getJobs(account.accountId());
assertEquals(2, jobs.size());
- var payments = ukelonn.getPayments(account.getAccountId());
+ var payments = ukelonn.getPayments(account.accountId());
assertEquals(1, payments.size());
// Try deleting the payment as a job
- var idsOfJobsToDelete = Arrays.asList(payments.get(0).getId());
- var jobsAfterAttemptedDelete = ukelonn.deleteJobsFromAccount(account.getAccountId(), idsOfJobsToDelete);
+ var idsOfJobsToDelete = Arrays.asList(payments.get(0).id());
+ var jobsAfterAttemptedDelete = ukelonn.deleteJobsFromAccount(account.accountId(), idsOfJobsToDelete);
// Verify that both the jobs and payments are unaffected
assertEquals(2, jobsAfterAttemptedDelete.size());
- var paymentsAfterAttemptedDelete = ukelonn.getPayments(account.getAccountId());
+ var paymentsAfterAttemptedDelete = ukelonn.getPayments(account.accountId());
assertEquals(1, paymentsAfterAttemptedDelete.size());
} finally {
restoreTestDatabase();
@@ -618,18 +618,18 @@ void verifyThatTryingToDeleteJobsOfDifferentAccountWillDoNothing() throws Except
var otherAccount = ukelonn.getAccount(otherUsername);
// Check the preconditions
- var jobs = ukelonn.getJobs(account.getAccountId());
+ var jobs = ukelonn.getJobs(account.accountId());
assertEquals(2, jobs.size());
- var otherAccountJobs = ukelonn.getJobs(otherAccount.getAccountId());
+ var otherAccountJobs = ukelonn.getJobs(otherAccount.accountId());
assertEquals(10, otherAccountJobs.size());
// Try deleting the payment as a job
- var idsOfJobsToDelete = Arrays.asList(otherAccountJobs.get(0).getId(), otherAccountJobs.get(1).getId(), otherAccountJobs.get(2).getId(), otherAccountJobs.get(3).getId(), otherAccountJobs.get(4).getId(), otherAccountJobs.get(5).getId(), otherAccountJobs.get(6).getId(), otherAccountJobs.get(7).getId(), otherAccountJobs.get(8).getId(), otherAccountJobs.get(9).getId());
- var jobsAfterAttemptedDelete = ukelonn.deleteJobsFromAccount(account.getAccountId(), idsOfJobsToDelete);
+ var idsOfJobsToDelete = Arrays.asList(otherAccountJobs.get(0).id(), otherAccountJobs.get(1).id(), otherAccountJobs.get(2).id(), otherAccountJobs.get(3).id(), otherAccountJobs.get(4).id(), otherAccountJobs.get(5).id(), otherAccountJobs.get(6).id(), otherAccountJobs.get(7).id(), otherAccountJobs.get(8).id(), otherAccountJobs.get(9).id());
+ var jobsAfterAttemptedDelete = ukelonn.deleteJobsFromAccount(account.accountId(), idsOfJobsToDelete);
// Verify that both the account's jobs and and the other account's jobs are unaffected
assertEquals(2, jobsAfterAttemptedDelete.size());
- var otherAccountsJobsAfterAttemptedDelete = ukelonn.getJobs(otherAccount.getAccountId());
+ var otherAccountsJobsAfterAttemptedDelete = ukelonn.getJobs(otherAccount.accountId());
assertThat(otherAccountsJobsAfterAttemptedDelete).containsAll(otherAccountJobs);
} finally {
restoreTestDatabase();
@@ -673,13 +673,13 @@ void testUpdateJob() throws Exception {
when(useradmin.getUser(anyString())).thenReturn(user);
ukelonn.setUserAdmin(useradmin);
var account = ukelonn.getAccount(username);
- var job = ukelonn.getJobs(account.getAccountId()).get(0);
- int jobId = job.getId();
+ var job = ukelonn.getJobs(account.accountId()).get(0);
+ int jobId = job.id();
// Save initial values of the job for comparison later
- var originalTransactionTypeId = job.getTransactionType().getId();
- var originalTransactionTime = job.getTransactionTime();
- var originalTransactionAmount = job.getTransactionAmount();
+ var originalTransactionTypeId = job.transactionType().id();
+ var originalTransactionTime = job.transactionTime();
+ var originalTransactionAmount = job.transactionAmount();
// Find a different job type that has a different amount
var newJobType = findJobTypeWithDifferentIdAndAmount(ukelonn, originalTransactionTypeId, originalTransactionAmount);
@@ -688,19 +688,19 @@ void testUpdateJob() throws Exception {
var now = new Date();
var editedJob = UpdatedTransaction.with()
.id(jobId)
- .accountId(account.getAccountId())
- .transactionTypeId(newJobType.getId())
+ .accountId(account.accountId())
+ .transactionTypeId(newJobType.id())
.transactionTime(now)
- .transactionAmount(newJobType.getTransactionAmount())
+ .transactionAmount(newJobType.transactionAmount())
.build();
var updatedJobs = ukelonn.updateJob(editedJob);
- var editedJobFromDatabase = updatedJobs.stream().filter(t->t.getId() == job.getId()).collect(Collectors.toList()).get(0);
+ var editedJobFromDatabase = updatedJobs.stream().filter(t->t.id() == job.id()).collect(Collectors.toList()).get(0);
- assertEquals(editedJob.getTransactionTypeId(), editedJobFromDatabase.getTransactionType().getId().intValue());
- assertThat(editedJobFromDatabase.getTransactionTime().getTime()).isGreaterThan(originalTransactionTime.getTime());
- assertEquals(editedJob.getTransactionAmount(), editedJobFromDatabase.getTransactionAmount(), 0.0);
+ assertEquals(editedJob.transactionTypeId(), editedJobFromDatabase.transactionType().id());
+ assertThat(editedJobFromDatabase.transactionTime().getTime()).isGreaterThan(originalTransactionTime.getTime());
+ assertEquals(editedJob.transactionAmount(), editedJobFromDatabase.transactionAmount(), 0.0);
} finally {
restoreTestDatabase();
}
@@ -725,7 +725,7 @@ void testUpdateJobGetSQLException() throws Exception {
}
private TransactionType findJobTypeWithDifferentIdAndAmount(UkelonnService ukelonn, Integer transactionTypeId, double amount) {
- return ukelonn.getJobTypes().stream().filter(t->!t.getId().equals(transactionTypeId)).filter(t->t.getTransactionAmount() != amount).collect(Collectors.toList()).get(0);
+ return ukelonn.getJobTypes().stream().filter(t->t.id() != transactionTypeId).filter(t->t.transactionAmount() != amount).collect(Collectors.toList()).get(0);
}
@Test
@@ -743,7 +743,7 @@ void testGetPayments() {
when(useradmin.getUser(anyString())).thenReturn(user);
ukelonn.setUserAdmin(useradmin);
var account = ukelonn.getAccount(username);
- var payments = ukelonn.getPayments(account.getAccountId());
+ var payments = ukelonn.getPayments(account.accountId());
assertEquals(10, payments.size());
}
@@ -813,12 +813,12 @@ void testRegisterPayment() {
// Create the request
var account = ukelonn.getAccount("jad");
- var originalBalance = account.getBalance();
+ var originalBalance = account.balance();
var paymenttypes = ukelonn.getPaymenttypes();
var payment = PerformedTransaction.with()
.account(account)
- .transactionTypeId(paymenttypes.get(0).getId())
- .transactionAmount(account.getBalance())
+ .transactionTypeId(paymenttypes.get(0).id())
+ .transactionAmount(account.balance())
.transactionDate(new Date())
.build();
@@ -826,8 +826,8 @@ void testRegisterPayment() {
var result = ukelonn.registerPayment(payment);
// Check the response
- assertEquals("jad", result.getUsername());
- assertThat(result.getBalance()).isLessThan(originalBalance);
+ assertEquals("jad", result.username());
+ assertThat(result.balance()).isLessThan(originalBalance);
}
@Test
@@ -931,7 +931,7 @@ void testModifyJobtype() {
// Find a jobtyoe
var jobtypes = ukelonn.getJobTypes();
var jobtype = jobtypes.get(0);
- var originalAmount = jobtype.getTransactionAmount();
+ var originalAmount = jobtype.transactionAmount();
// Modify the amount of the jobtype
jobtype = TransactionType.with(jobtype).transactionAmount(originalAmount + 1).build();
@@ -941,7 +941,7 @@ void testModifyJobtype() {
// Verify that the updated amount is larger than the original amount
var updatedJobtype = updatedJobtypes.get(0);
- assertThat(updatedJobtype.getTransactionAmount()).isGreaterThan(originalAmount);
+ assertThat(updatedJobtype.transactionAmount()).isGreaterThan(originalAmount);
}
@Test
@@ -1031,7 +1031,7 @@ void testModifyPaymenttype() {
// Find a payment type
var paymenttypes = ukelonn.getPaymenttypes();
var paymenttype = paymenttypes.get(0);
- var originalAmount = paymenttype.getTransactionAmount();
+ var originalAmount = paymenttype.transactionAmount();
// Modify the amount of the payment type
paymenttype = TransactionType.with(paymenttype).transactionAmount(originalAmount + 1).build();
@@ -1041,7 +1041,7 @@ void testModifyPaymenttype() {
// Verify that the updated amount is larger than the original amount
var updatedPaymenttype = updatedPaymenttypes.get(0);
- assertThat(updatedPaymenttype.getTransactionAmount()).isGreaterThan(originalAmount);
+ assertThat(updatedPaymenttype.transactionAmount()).isGreaterThan(originalAmount);
}
@Test
@@ -1148,15 +1148,15 @@ void testPasswordsEqualAndNotEmpty() {
void testHasUserWithNonEmptyUsername() {
var passwords = PasswordsWithUser.with().build();
var userWithUsername = User.with().userId(1).username("foo").build();
- passwords.setUser(userWithUsername);
+ passwords = PasswordsWithUser.with(passwords).user(userWithUsername).build();
assertTrue(UkelonnServiceProvider.hasUserWithNonEmptyUsername(passwords));
var userWithEmptyUsername = User.with().userId(1).username("").build();
- passwords.setUser(userWithEmptyUsername);
+ passwords = PasswordsWithUser.with(passwords).user(userWithEmptyUsername).build();
assertFalse(UkelonnServiceProvider.hasUserWithNonEmptyUsername(passwords));
var userWithNullUsername = User.with().userId(1).username(null).build();
- passwords.setUser(userWithNullUsername);
+ passwords = PasswordsWithUser.with(passwords).user(userWithNullUsername).build();
assertFalse(UkelonnServiceProvider.hasUserWithNonEmptyUsername(passwords));
- passwords.setUser(null);
+ passwords = PasswordsWithUser.with(passwords).user(null).build();
assertFalse(UkelonnServiceProvider.hasUserWithNonEmptyUsername(passwords));
}
@@ -1196,7 +1196,7 @@ void testJoinIds() {
var ukelonn = getUkelonnServiceSingleton();
ukelonn.setUserAdmin(useradmin);
var account = ukelonn.getAccount("jad");
- var jobs = ukelonn.getJobs(account.getAccountId()).stream().map(Transaction::getId).collect(Collectors.toList());
+ var jobs = ukelonn.getJobs(account.accountId()).stream().map(Transaction::id).collect(Collectors.toList());
assertEquals("31, 33, 34, 35, 37, 38, 39, 41, 42, 43", UkelonnServiceProvider.joinIds(jobs).toString());
}
@@ -1245,8 +1245,8 @@ void testEarningsSumOverYear() {
var statistics = ukelonn.earningsSumOverYear("jad");
assertThat(statistics).isNotEmpty();
var firstYear = statistics.get(0);
- assertEquals(1250.0, firstYear.getSum(), 0.0);
- assertEquals(2016, firstYear.getYear());
+ assertEquals(1250.0, firstYear.sum(), 0.0);
+ assertEquals(2016, firstYear.year());
}
@Test
@@ -1279,9 +1279,9 @@ void testEarningsSumOverMonth() {
var statistics = ukelonn.earningsSumOverMonth("jad");
assertThat(statistics).isNotEmpty();
var firstYear = statistics.get(0);
- assertEquals(125.0, firstYear.getSum(), 0.0);
- assertEquals(2016, firstYear.getYear());
- assertEquals(7, firstYear.getMonth());
+ assertEquals(125.0, firstYear.sum(), 0.0);
+ assertEquals(2016, firstYear.year());
+ assertEquals(7, firstYear.month());
}
@Test
@@ -1331,7 +1331,7 @@ void testGetCreateModifyAndDeleteBonuses() {
.startDate(julestart)
.endDate(juleslutt)
.build();
- var enabledBonus = ukelonn.createBonus(julebonus).stream().filter(b -> "Julebonus".equals(b.getTitle())).findFirst().get();
+ var enabledBonus = ukelonn.createBonus(julebonus).stream().filter(b -> "Julebonus".equals(b.title())).findFirst().get();
var bonusCountWithOneAddedBonus = ukelonn.getAllBonuses().size();
assertThat(bonusCountWithOneAddedBonus).isGreaterThan(initialBonusCount);
@@ -1350,8 +1350,8 @@ void testGetCreateModifyAndDeleteBonuses() {
.bonusFactor(1.25)
.startDate(julestart)
.endDate(juleslutt)
- .build()).stream().filter(b -> "Julebonuz".equals(b.getTitle())).findFirst().get();
- var expectAmount2 = julebonus.getBonusFactor() * amount + julebonus2.getBonusFactor() * amount - amount;
+ .build()).stream().filter(b -> "Julebonuz".equals(b.title())).findFirst().get();
+ var expectAmount2 = julebonus.bonusFactor() * amount + julebonus2.bonusFactor() * amount - amount;
assertEquals(expectAmount2, ukelonn.addBonus(amount), 0.0);
ukelonn.deleteBonus(julebonus2);
@@ -1368,7 +1368,7 @@ void testGetCreateModifyAndDeleteBonuses() {
.startDate(paaskestart)
.endDate(paaskeslutt)
.build();
- var inactiveBonus = ukelonn.createBonus(paaskebonus).stream().filter(b -> "PĂ„skebonus".equals(b.getTitle())).findFirst().get();
+ var inactiveBonus = ukelonn.createBonus(paaskebonus).stream().filter(b -> "PĂ„skebonus".equals(b.title())).findFirst().get();
assertThat(ukelonn.getAllBonuses()).hasSizeGreaterThan(bonusCountWithOneAddedBonus);
// Verify that active count is larger than 0 and is less than total count
@@ -1383,13 +1383,13 @@ void testGetCreateModifyAndDeleteBonuses() {
// Change the enabled bonus to set the enabled flag to false, and keep the rest of the values
// (ie. deactivate the currenly active bonus)
var bonuses = ukelonn.modifyBonus(disableBonus(enabledBonus));
- var disabledBonus = bonuses.stream().filter(b -> b.getBonusId() == enabledBonus.getBonusId()).findFirst().get();
- assertFalse(disabledBonus.isEnabled());
- assertEquals(enabledBonus.getTitle(), disabledBonus.getTitle());
- assertEquals(enabledBonus.getDescription(), disabledBonus.getDescription());
- assertEquals(enabledBonus.getBonusFactor(), disabledBonus.getBonusFactor(), 0.0);
- assertEquals(enabledBonus.getStartDate(), disabledBonus.getStartDate());
- assertEquals(enabledBonus.getEndDate(), disabledBonus.getEndDate());
+ var disabledBonus = bonuses.stream().filter(b -> b.bonusId() == enabledBonus.bonusId()).findFirst().get();
+ assertFalse(disabledBonus.enabled());
+ assertEquals(enabledBonus.title(), disabledBonus.title());
+ assertEquals(enabledBonus.description(), disabledBonus.description());
+ assertEquals(enabledBonus.bonusFactor(), disabledBonus.bonusFactor(), 0.0);
+ assertEquals(enabledBonus.startDate(), disabledBonus.startDate());
+ assertEquals(enabledBonus.endDate(), disabledBonus.endDate());
// Verify that the active bonus count is less than before the update
assertThat(ukelonn.getActiveBonuses()).hasSizeLessThan(activeBonusCount);
@@ -1603,6 +1603,6 @@ void testDisplayTextsForDefaultLocale() {
}
private Bonus disableBonus(Bonus bonus) {
- return Bonus.with().bonusId(bonus.getBonusId()).enabled(false).iconurl(bonus.getIconurl()).title(bonus.getTitle()).description(bonus.getDescription()).bonusFactor(bonus.getBonusFactor()).startDate(bonus.getStartDate()).endDate(bonus.getEndDate()).build();
+ return Bonus.with().bonusId(bonus.bonusId()).enabled(false).iconurl(bonus.iconurl()).title(bonus.title()).description(bonus.description()).bonusFactor(bonus.bonusFactor()).startDate(bonus.startDate()).endDate(bonus.endDate()).build();
}
}
diff --git a/ukelonn.db.liquibase.production/src/main/java/no/priv/bang/ukelonn/db/liquibase/production/ProductionLiquibaseRunner.java b/ukelonn.db.liquibase.production/src/main/java/no/priv/bang/ukelonn/db/liquibase/production/ProductionLiquibaseRunner.java
index 89f5970d..caf7b847 100644
--- a/ukelonn.db.liquibase.production/src/main/java/no/priv/bang/ukelonn/db/liquibase/production/ProductionLiquibaseRunner.java
+++ b/ukelonn.db.liquibase.production/src/main/java/no/priv/bang/ukelonn/db/liquibase/production/ProductionLiquibaseRunner.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016-2023 Steinar Bang
+ * Copyright 2016-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,7 +15,8 @@
*/
package no.priv.bang.ukelonn.db.liquibase.production;
-import java.sql.Connection;
+import static liquibase.command.core.helpers.DbUrlConnectionArgumentsCommandStep.DATABASE_ARG;
+
import java.sql.SQLException;
import java.util.Map;
@@ -35,7 +36,6 @@
import liquibase.command.CommandScope;
import liquibase.command.core.UpdateCommandStep;
import liquibase.command.core.helpers.DatabaseChangelogCommandStep;
-import liquibase.command.core.helpers.DbUrlConnectionCommandStep;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.resource.ClassLoaderResourceAccessor;
@@ -62,7 +62,7 @@ public void activate(Map config) {
@Override
public void prepare(DataSource datasource) throws SQLException {
try {
- UkelonnLiquibase liquibase = createUkelonnLiquibase();
+ var liquibase = createUkelonnLiquibase();
liquibase.createInitialSchema(datasource);
insertInitialDataInDatabase(datasource);
liquibase.updateSchema(datasource);
@@ -72,14 +72,14 @@ public void prepare(DataSource datasource) throws SQLException {
}
boolean insertInitialDataInDatabase(DataSource datasource) {
- try(Connection connect = datasource.getConnection()) {
+ try(var connect = datasource.getConnection()) {
try (var database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connect))) {
Map scopeObjects = Map.of(
Scope.Attr.database.name(), database,
Scope.Attr.resourceAccessor.name(), new ClassLoaderResourceAccessor(getClass().getClassLoader()));
Scope.child(scopeObjects, (ScopedRunner>) () -> new CommandScope("update")
- .addArgumentValue(DbUrlConnectionCommandStep.DATABASE_ARG, database)
+ .addArgumentValue(DATABASE_ARG, database)
.addArgumentValue(UpdateCommandStep.CHANGELOG_FILE_ARG, initialDataResourceName())
.addArgumentValue(DatabaseChangelogCommandStep.CHANGELOG_PARAMETERS, new ChangeLogParameters(database))
.execute());
diff --git a/ukelonn.db.liquibase.test/src/main/java/no/priv/bang/ukelonn/db/liquibase/test/TestLiquibaseRunner.java b/ukelonn.db.liquibase.test/src/main/java/no/priv/bang/ukelonn/db/liquibase/test/TestLiquibaseRunner.java
index 78b9ec0b..9afc2de7 100644
--- a/ukelonn.db.liquibase.test/src/main/java/no/priv/bang/ukelonn/db/liquibase/test/TestLiquibaseRunner.java
+++ b/ukelonn.db.liquibase.test/src/main/java/no/priv/bang/ukelonn/db/liquibase/test/TestLiquibaseRunner.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016-2023 Steinar Bang
+ * Copyright 2016-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,8 +15,8 @@
*/
package no.priv.bang.ukelonn.db.liquibase.test;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
+import static liquibase.command.core.helpers.DbUrlConnectionArgumentsCommandStep.DATABASE_ARG;
+
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
@@ -41,9 +41,6 @@
import liquibase.command.CommandScope;
import liquibase.command.core.UpdateCommandStep;
import liquibase.command.core.helpers.DatabaseChangelogCommandStep;
-import liquibase.command.core.helpers.DbUrlConnectionCommandStep;
-import liquibase.database.Database;
-import liquibase.database.DatabaseConnection;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.DatabaseException;
@@ -69,7 +66,7 @@ public void activate(Map config) {
@Override
public void prepare(DataSource datasource) throws SQLException {
- UkelonnLiquibase liquibase = new UkelonnLiquibase();
+ var liquibase = new UkelonnLiquibase();
try {
liquibase.createInitialSchema(datasource);
insertMockData(datasource);
@@ -80,14 +77,14 @@ public void prepare(DataSource datasource) throws SQLException {
}
public boolean insertMockData(DataSource datasource) {
- try(Connection connect = datasource.getConnection()) {
+ try(var connect = datasource.getConnection()) {
try (var database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connect))) {
Map scopeObjects = Map.of(
Scope.Attr.database.name(), database,
Scope.Attr.resourceAccessor.name(), new ClassLoaderResourceAccessor(getClass().getClassLoader()));
Scope.child(scopeObjects, (ScopedRunner>) () -> new CommandScope("update")
- .addArgumentValue(DbUrlConnectionCommandStep.DATABASE_ARG, database)
+ .addArgumentValue(DATABASE_ARG, database)
.addArgumentValue(UpdateCommandStep.CHANGELOG_FILE_ARG, dummyDataResourceName())
.addArgumentValue(DatabaseChangelogCommandStep.CHANGELOG_PARAMETERS, new ChangeLogParameters(database))
.execute());
@@ -101,16 +98,16 @@ public boolean insertMockData(DataSource datasource) {
}
public boolean rollbackMockData(DataSource datasource) {
- try(Connection connect = datasource.getConnection()) {
- DatabaseConnection databaseConnection = new JdbcConnection(connect);
+ try(var connect = datasource.getConnection()) {
+ var databaseConnection = new JdbcConnection(connect);
try(var classLoaderResourceAccessor = new ClassLoaderResourceAccessor(getClass().getClassLoader())) {
- try(PreparedStatement statement = connect.prepareStatement("delete from user_roles")) {
+ try(var statement = connect.prepareStatement("delete from user_roles")) {
statement.executeUpdate();
}
- try(PreparedStatement statement = connect.prepareStatement("delete from users")) {
+ try(var statement = connect.prepareStatement("delete from users")) {
statement.executeUpdate();
}
- Liquibase liquibase = new Liquibase(dummyDataResourceName(), classLoaderResourceAccessor, databaseConnection);
+ var liquibase = new Liquibase(dummyDataResourceName(), classLoaderResourceAccessor, databaseConnection);
liquibase.rollback(3, "");
}
return true;
@@ -129,9 +126,9 @@ public boolean rollbackMockData(DataSource datasource) {
* @throws SQLException
*/
List getChangeLogHistory(DataSource datasource) throws DatabaseException, SQLException {
- try(Connection connect = datasource.getConnection()) {
+ try(var connect = datasource.getConnection()) {
try(var databaseConnection = new JdbcConnection(connect)) {
- Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(databaseConnection);
+ var database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(databaseConnection);
var logHistoryService = Scope.getCurrentScope().getSingleton(ChangeLogHistoryServiceFactory.class).getChangeLogService(database);
return logHistoryService.getRanChangeSets();
} catch (Exception e) {
diff --git a/ukelonn.db.liquibase.test/src/test/java/no/priv/bang/ukelonn/db/liquibase/test/TestLiquibaseRunnerTest.java b/ukelonn.db.liquibase.test/src/test/java/no/priv/bang/ukelonn/db/liquibase/test/TestLiquibaseRunnerTest.java
index 2d11eea1..073d58f3 100644
--- a/ukelonn.db.liquibase.test/src/test/java/no/priv/bang/ukelonn/db/liquibase/test/TestLiquibaseRunnerTest.java
+++ b/ukelonn.db.liquibase.test/src/test/java/no/priv/bang/ukelonn/db/liquibase/test/TestLiquibaseRunnerTest.java
@@ -46,7 +46,6 @@
import liquibase.command.CommandScope;
import liquibase.command.core.UpdateCommandStep;
import liquibase.command.core.helpers.DatabaseChangelogCommandStep;
-import liquibase.command.core.helpers.DbUrlConnectionCommandStep;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.DatabaseException;
@@ -55,6 +54,8 @@
import no.priv.bang.osgi.service.mocks.logservice.MockLogService;
import no.priv.bang.ukelonn.UkelonnException;
import no.priv.bang.ukelonn.db.liquibase.UkelonnLiquibase;
+
+import static liquibase.command.core.helpers.DbUrlConnectionArgumentsCommandStep.DATABASE_ARG;
import static no.priv.bang.ukelonn.db.liquibase.test.TestLiquibaseRunner.*;
class TestLiquibaseRunnerTest {
@@ -416,7 +417,7 @@ void addUkelonnSchemaAndDataToDerbyServer() throws SQLException, LiquibaseExcept
Scope.Attr.resourceAccessor.name(), new ClassLoaderResourceAccessor(getClass().getClassLoader()));
Scope.child(scopeObjects, (ScopedRunner>) () -> new CommandScope("update")
- .addArgumentValue(DbUrlConnectionCommandStep.DATABASE_ARG, database)
+ .addArgumentValue(DATABASE_ARG, database)
.addArgumentValue(UpdateCommandStep.CHANGELOG_FILE_ARG, "sql/data/db-changelog.xml")
.addArgumentValue(DatabaseChangelogCommandStep.CHANGELOG_PARAMETERS, new ChangeLogParameters(database))
.execute());
diff --git a/ukelonn.db.liquibase/src/main/java/no/priv/bang/ukelonn/db/liquibase/UkelonnLiquibase.java b/ukelonn.db.liquibase/src/main/java/no/priv/bang/ukelonn/db/liquibase/UkelonnLiquibase.java
index 342a42d8..5921c8cc 100644
--- a/ukelonn.db.liquibase/src/main/java/no/priv/bang/ukelonn/db/liquibase/UkelonnLiquibase.java
+++ b/ukelonn.db.liquibase/src/main/java/no/priv/bang/ukelonn/db/liquibase/UkelonnLiquibase.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016-2023 Steinar Bang
+ * Copyright 2016-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,8 @@
*/
package no.priv.bang.ukelonn.db.liquibase;
+import static liquibase.command.core.helpers.DbUrlConnectionArgumentsCommandStep.DATABASE_ARG;
+
import java.util.Map;
import javax.sql.DataSource;
@@ -25,7 +27,6 @@
import liquibase.command.CommandScope;
import liquibase.command.core.UpdateCommandStep;
import liquibase.command.core.helpers.DatabaseChangelogCommandStep;
-import liquibase.command.core.helpers.DbUrlConnectionCommandStep;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.LiquibaseException;
@@ -47,7 +48,7 @@ public void createInitialSchema(DataSource datasource) throws LiquibaseException
Scope.Attr.resourceAccessor.name(), new ClassLoaderResourceAccessor(getClass().getClassLoader()));
Scope.child(scopeObjects, (ScopedRunner>) () -> new CommandScope(UPDATE)
- .addArgumentValue(DbUrlConnectionCommandStep.DATABASE_ARG, database)
+ .addArgumentValue(DATABASE_ARG, database)
.addArgumentValue(UpdateCommandStep.CHANGELOG_FILE_ARG, "ukelonn-db-changelog/db-changelog-1.0.0.xml")
.addArgumentValue(DatabaseChangelogCommandStep.CHANGELOG_PARAMETERS, new ChangeLogParameters(database))
.execute());
@@ -67,7 +68,7 @@ public void updateSchema(DataSource datasource) throws LiquibaseException {
Scope.Attr.resourceAccessor.name(), new ClassLoaderResourceAccessor(getClass().getClassLoader()));
Scope.child(scopeObjects, (ScopedRunner>) () -> new CommandScope(UPDATE)
- .addArgumentValue(DbUrlConnectionCommandStep.DATABASE_ARG, database)
+ .addArgumentValue(DATABASE_ARG, database)
.addArgumentValue(UpdateCommandStep.CHANGELOG_FILE_ARG, "ukelonn-db-changelog/db-changelog-1.0.1.xml")
.addArgumentValue(DatabaseChangelogCommandStep.CHANGELOG_PARAMETERS, new ChangeLogParameters(database))
.execute());
@@ -79,7 +80,7 @@ public void updateSchema(DataSource datasource) throws LiquibaseException {
}
try (var connect = datasource.getConnection()) {
- AuthserviceLiquibase authserviceLiquibase = new AuthserviceLiquibase();
+ var authserviceLiquibase = new AuthserviceLiquibase();
authserviceLiquibase.createInitialSchema(connect);
} catch (LiquibaseException | AuthserviceException e) {
throw e;
@@ -94,7 +95,7 @@ public void updateSchema(DataSource datasource) throws LiquibaseException {
Scope.Attr.resourceAccessor.name(), new ClassLoaderResourceAccessor(getClass().getClassLoader()));
Scope.child(scopeObjects, (ScopedRunner>) () -> new CommandScope(UPDATE)
- .addArgumentValue(DbUrlConnectionCommandStep.DATABASE_ARG, database)
+ .addArgumentValue(DATABASE_ARG, database)
.addArgumentValue(UpdateCommandStep.CHANGELOG_FILE_ARG, "ukelonn-db-changelog/db-changelog.xml")
.addArgumentValue(DatabaseChangelogCommandStep.CHANGELOG_PARAMETERS, new ChangeLogParameters(database))
.execute());
diff --git a/ukelonn.services/pom.xml b/ukelonn.services/pom.xml
index 6c539fcb..3c973a49 100644
--- a/ukelonn.services/pom.xml
+++ b/ukelonn.services/pom.xml
@@ -71,12 +71,6 @@
beans.immutable
provided
-
- no.priv.bang.beans
- beans.immutable
- xml
- features
-
org.apache.commons
commons-lang3
diff --git a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Account.java b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Account.java
index 80cd6b44..cf9b9a24 100644
--- a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Account.java
+++ b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Account.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016-2021 Steinar Bang
+ * Copyright 2016-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,105 +17,69 @@
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-import no.priv.bang.beans.immutable.Immutable;
-
@JsonIgnoreProperties(ignoreUnknown=true)
-public class Account extends Immutable { // NOSONAR Immutable handles added fields
- private int accountId;
- private String username;
- private String firstName;
- private String lastName;
- private double balance;
-
- private Account() {
- // No-arg constructor required by jackson
- }
-
- public int getAccountId() {
- return accountId;
- }
-
- public String getUsername() {
- return username;
- }
-
- public String getFirstName() {
- return firstName;
- }
-
- public String getLastName() {
- return lastName;
- }
+public record Account(int accountId, String username,String firstName, String lastName, double balance) {
public String getFullName() {
- if (getFirstName() != null && getLastName() != null) {
- return getFirstName() + " " + getLastName();
+ if (firstName() != null && lastName() != null) {
+ return firstName() + " " + lastName();
}
- if (getFirstName() != null) {
- return getFirstName();
+ if (firstName() != null) {
+ return firstName();
}
- return getUsername();
- }
-
- public double getBalance() {
- return balance;
- }
-
- public void setBalance(double balance) {
- this.balance = balance;
+ return username();
}
- @Override
- public String toString() {
- return "Account [getAccountId()=" + getAccountId() + ", getUsername()=" + getUsername() + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]";
+ public static Builder with() {
+ return new Builder();
}
- public static AccountBuilder with() {
- return new AccountBuilder();
+ public static Builder with(Account account) {
+ var builder = new Builder();
+ builder.accountid = account.accountId;
+ builder.username = account.username;
+ builder.firstName = account.firstName;
+ builder.lastName = account.lastName;
+ builder.balance = account.balance;
+ return builder;
}
- public static class AccountBuilder {
+ public static class Builder {
private int accountid;
private String username;
private String firstName;
private String lastName;
private double balance;
- private AccountBuilder() {}
+ private Builder() {}
public Account build() {
- Account account = new Account();
- account.accountId = this.accountid;
- account.username = this.username;
- account.firstName = this.firstName;
- account.lastName = this.lastName;
- account.balance = this.balance;
- return account;
+ return new Account(this.accountid, this.username, this.firstName, this.lastName, this.balance);
}
- public AccountBuilder accountid(int accountid) {
+ public Builder accountid(int accountid) {
this.accountid = accountid;
return this;
}
- public AccountBuilder username(String username) {
+ public Builder username(String username) {
this.username = username;
return this;
}
- public AccountBuilder firstName(String firstName) {
+ public Builder firstName(String firstName) {
this.firstName = firstName;
return this;
}
- public AccountBuilder lastName(String lastName) {
+ public Builder lastName(String lastName) {
this.lastName = lastName;
return this;
}
- public AccountBuilder balance(double balance) {
+ public Builder balance(double balance) {
this.balance = balance;
return this;
}
diff --git a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/AccountWithJobIds.java b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/AccountWithJobIds.java
index 6211c95a..f9f2a145 100644
--- a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/AccountWithJobIds.java
+++ b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/AccountWithJobIds.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2018-2021 Steinar Bang
+ * Copyright 2018-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,43 +18,27 @@
import java.util.Collections;
import java.util.List;
-public class AccountWithJobIds {
- Account account;
- List jobIds;
+public record AccountWithJobIds(Account account, List jobIds) {
- private AccountWithJobIds() {
- // No-args constructor required by jackson
+ public static Builder with() {
+ return new Builder();
}
- public Account getAccount() {
- return account;
- }
- public List getJobIds() {
- return jobIds;
- }
-
- public static AccountWithJobIdsBuilder with() {
- return new AccountWithJobIdsBuilder();
- }
-
- public static class AccountWithJobIdsBuilder {
+ public static class Builder {
private Account account;
List jobIds = Collections.emptyList();
public AccountWithJobIds build() {
- AccountWithJobIds accountWithJobIds = new AccountWithJobIds();
- accountWithJobIds.account = this.account;
- accountWithJobIds.jobIds = this.jobIds;
- return accountWithJobIds;
+ return new AccountWithJobIds(this.account, this.jobIds);
}
- public AccountWithJobIdsBuilder account(Account account) {
+ public Builder account(Account account) {
this.account = account;
return this;
}
- public AccountWithJobIdsBuilder jobIds(List jobIds) {
+ public Builder jobIds(List jobIds) {
this.jobIds = jobIds;
return this;
}
diff --git a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Bonus.java b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Bonus.java
index e5cb625a..ac24288b 100644
--- a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Bonus.java
+++ b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Bonus.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2020-2021 Steinar Bang
+ * Copyright 2020-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,58 +17,22 @@
import java.util.Date;
-import no.priv.bang.beans.immutable.Immutable;
-
-public class Bonus extends Immutable { // NOSONAR Immutable handles added fields
- int bonusId;
- private boolean enabled;
- private String iconurl;
- private String title;
- private String description;
- private double bonusFactor;
- private Date startDate;
- private Date endDate;
-
- private Bonus() { }
-
- public int getBonusId() {
- return bonusId;
- }
-
- public boolean isEnabled() {
- return enabled;
- }
-
- public String getIconurl() {
- return iconurl;
- }
-
- public String getTitle() {
- return title;
- }
-
- public String getDescription() {
- return description;
- }
-
- public double getBonusFactor() {
- return bonusFactor;
- }
-
- public Date getStartDate() {
- return startDate;
+public record Bonus(
+ int bonusId,
+ boolean enabled,
+ String iconurl,
+ String title,
+ String description,
+ double bonusFactor,
+ Date startDate,
+ Date endDate)
+{
+
+ public static Builder with() {
+ return new Builder();
}
- public Date getEndDate() {
- return endDate;
- }
-
- public static BonusBuilder with() {
- return new BonusBuilder();
- }
-
- public static class BonusBuilder {
-
+ public static class Builder {
private int bonusId;
private boolean enabled;
private String iconurl;
@@ -78,57 +42,48 @@ public static class BonusBuilder {
private Date startDate;
private Date endDate;
- private BonusBuilder() { }
+ private Builder() { }
public Bonus build() {
- Bonus bonus = new Bonus();
- bonus.bonusId = this.bonusId;
- bonus.enabled = this.enabled;
- bonus.iconurl = this.iconurl;
- bonus.title = this.title;
- bonus.description = this.description;
- bonus.bonusFactor = this.bonusFactor;
- bonus.startDate = this.startDate;
- bonus.endDate = this.endDate;
- return bonus;
+ return new Bonus(bonusId, enabled, iconurl, title, description, bonusFactor, startDate, endDate);
}
- public BonusBuilder bonusId(int bonusId) {
+ public Builder bonusId(int bonusId) {
this.bonusId = bonusId;
return this;
}
- public BonusBuilder enabled(boolean enabled) {
+ public Builder enabled(boolean enabled) {
this.enabled = enabled;
return this;
}
- public BonusBuilder iconurl(String iconurl) {
+ public Builder iconurl(String iconurl) {
this.iconurl = iconurl;
return this;
}
- public BonusBuilder title(String title) {
+ public Builder title(String title) {
this.title = title;
return this;
}
- public BonusBuilder description(String description) {
+ public Builder description(String description) {
this.description = description;
return this;
}
- public BonusBuilder bonusFactor(double bonusFactor) {
+ public Builder bonusFactor(double bonusFactor) {
this.bonusFactor = bonusFactor;
return this;
}
- public BonusBuilder startDate(Date startDate) {
+ public Builder startDate(Date startDate) {
this.startDate = startDate;
return this;
}
- public BonusBuilder endDate(Date endDate) {
+ public Builder endDate(Date endDate) {
this.endDate = endDate;
return this;
}
diff --git a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/LocaleBean.java b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/LocaleBean.java
index da1e4763..018d27bd 100644
--- a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/LocaleBean.java
+++ b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/LocaleBean.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2020-2021 Steinar Bang
+ * Copyright 2020-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,41 +16,26 @@
package no.priv.bang.ukelonn.beans;
import java.util.Locale;
+import java.util.Optional;
-import no.priv.bang.beans.immutable.Immutable;
+public record LocaleBean(String code, String displayLanguage) {
-public class LocaleBean extends Immutable { // NOSONAR Immutable handles added fields
-
- private String code;
- private String displayLanguage;
-
- private LocaleBean() {}
-
- public String getCode() {
- return code;
- }
-
- public String getDisplayLanguage() {
- return displayLanguage;
- }
-
- public static LocaleBeanBuilder with() {
- return new LocaleBeanBuilder();
+ public static Builder with() {
+ return new Builder();
}
- public static class LocaleBeanBuilder {
+ public static class Builder {
private Locale locale;
- private LocaleBeanBuilder() {}
+ private Builder() {}
public LocaleBean build() {
- LocaleBean localeBean = new LocaleBean();
- localeBean.code = locale != null ? locale.toString() : null;
- localeBean.displayLanguage = locale != null ? locale.getDisplayLanguage(locale) : null;
- return localeBean;
+ String locale = Optional.ofNullable(this.locale).map(l -> l.toString()).orElse(null);
+ String displayLanguage = Optional.ofNullable(this.locale).map(l -> l.getDisplayLanguage(l)).orElse(null);
+ return new LocaleBean(locale, displayLanguage);
}
- public LocaleBeanBuilder locale(Locale locale) {
+ public Builder locale(Locale locale) {
this.locale = locale;
return this;
}
diff --git a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Notification.java b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Notification.java
index 469c1b54..761a6c1f 100644
--- a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Notification.java
+++ b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Notification.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016-2021 Steinar Bang
+ * Copyright 2016-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,44 +15,28 @@
*/
package no.priv.bang.ukelonn.beans;
-public class Notification {
+public record Notification(String title, String message) {
- private String title;
- private String message;
-
- private Notification() {}
-
- public String getTitle() {
- return title;
- }
-
- public String getMessage() {
- return message;
- }
-
- public static NotificationBuilder with() {
- return new NotificationBuilder();
+ public static Builder with() {
+ return new Builder();
}
- public static class NotificationBuilder {
+ public static class Builder {
private String title = "";
private String message = "";
- private NotificationBuilder() {}
+ private Builder() {}
public Notification build() {
- Notification notification = new Notification();
- notification.title = this.title;
- notification.message = this.message;
- return notification;
+ return new Notification(this.title, this.message);
}
- public NotificationBuilder title(String title) {
+ public Builder title(String title) {
this.title = title;
return this;
}
- public NotificationBuilder message(String message) {
+ public Builder message(String message) {
this.message = message;
return this;
}
diff --git a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/PasswordsWithUser.java b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/PasswordsWithUser.java
index 1d2495d4..90834e1e 100644
--- a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/PasswordsWithUser.java
+++ b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/PasswordsWithUser.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016-2021 Steinar Bang
+ * Copyright 2016-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,60 +15,42 @@
*/
package no.priv.bang.ukelonn.beans;
-public class PasswordsWithUser {
+public record PasswordsWithUser(User user, String password, String password2) {
- private User user;
- private String password;
- private String password2;
-
- private PasswordsWithUser() {}
-
- public User getUser() {
- return user;
- }
-
- public void setUser(User user) {
- this.user = user;
- }
-
- public String getPassword() {
- return password;
- }
-
- public String getPassword2() {
- return password2;
+ public static Builder with() {
+ return new Builder();
}
- public static PasswordsWithUserBuilder with() {
- return new PasswordsWithUserBuilder();
+ public static Builder with(PasswordsWithUser passwordsWithUser) {
+ var builder = new Builder();
+ builder.user = passwordsWithUser.user();
+ builder.password = passwordsWithUser.password();
+ builder.password2 = passwordsWithUser.password2;
+ return builder;
}
- public static class PasswordsWithUserBuilder {
+ public static class Builder {
private User user;
private String password;
private String password2;
- private PasswordsWithUserBuilder() {}
+ private Builder() {}
public PasswordsWithUser build() {
- PasswordsWithUser passwords = new PasswordsWithUser();
- passwords.user = this.user;
- passwords.password = this.password;
- passwords.password2 = this.password2;
- return passwords;
+ return new PasswordsWithUser(this.user, this.password, this.password2);
}
- public PasswordsWithUserBuilder user(User user) {
+ public Builder user(User user) {
this.user = user;
return this;
}
- public PasswordsWithUserBuilder password(String password) {
+ public Builder password(String password) {
this.password = password;
return this;
}
- public PasswordsWithUserBuilder password2(String password2) {
+ public Builder password2(String password2) {
this.password2 = password2;
return this;
}
diff --git a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/PerformedTransaction.java b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/PerformedTransaction.java
index 2c887004..2de1c319 100644
--- a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/PerformedTransaction.java
+++ b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/PerformedTransaction.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2018-2021 Steinar Bang
+ * Copyright 2018-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,70 +15,47 @@
*/
package no.priv.bang.ukelonn.beans;
-import java.util.Date;
-
-public class PerformedTransaction {
-
- private Account account = null;
- private int transactionTypeId;
- private double transactionAmount;
- private Date transactionDate;
-
- private PerformedTransaction() {}
-
- public Account getAccount() {
- return account;
- }
+import static java.util.Optional.ofNullable;
- public int getTransactionTypeId() {
- return transactionTypeId;
- }
-
- public double getTransactionAmount() {
- return transactionAmount;
- }
+import java.util.Date;
- public Date getTransactionDate() {
- return transactionDate;
- }
+public record PerformedTransaction(Account account, int transactionTypeId, double transactionAmount, Date transactionDate) {
- public static PerformedTransactionBuilder with() {
- return new PerformedTransactionBuilder();
+ public static Builder with() {
+ return new Builder();
}
- public static class PerformedTransactionBuilder {
+ public static class Builder {
private Account account;
private Integer transactionTypeId;
private Double transactionAmount;
private Date transactionDate;
- private PerformedTransactionBuilder() {}
+ private Builder() {}
public PerformedTransaction build() {
- PerformedTransaction performedTransaction = new PerformedTransaction();
- performedTransaction.account = this.account;
- performedTransaction.transactionTypeId = this.transactionTypeId != null ? this.transactionTypeId : -1;
- performedTransaction.transactionAmount = this.transactionAmount != null ? this.transactionAmount : 0.0;
- performedTransaction.transactionDate = this.transactionDate != null ? this.transactionDate : new Date();
- return performedTransaction;
+ var transactionTypeId = ofNullable(this.transactionTypeId).orElse(-1);
+ var transactionAmount = ofNullable(this.transactionAmount).orElse(0.0);
+ var transactionDate = ofNullable(this.transactionDate).orElse(new Date());
+ return new PerformedTransaction(this.account, transactionTypeId, transactionAmount, transactionDate);
}
- public PerformedTransactionBuilder account(Account account) {
+ public Builder account(Account account) {
this.account = account;
return this;
}
- public PerformedTransactionBuilder transactionTypeId(Integer transactionTypeId) {
+ public Builder transactionTypeId(Integer transactionTypeId) {
this.transactionTypeId = transactionTypeId;
return this;
}
- public PerformedTransactionBuilder transactionAmount(Double transactionAmount) {
+ public Builder transactionAmount(Double transactionAmount) {
this.transactionAmount = transactionAmount;
return this;
}
- public PerformedTransactionBuilder transactionDate(Date transactionDate) {
+ public Builder transactionDate(Date transactionDate) {
this.transactionDate = transactionDate;
return this;
}
diff --git a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/SumYear.java b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/SumYear.java
index 209a9d43..06ee2608 100644
--- a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/SumYear.java
+++ b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/SumYear.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2019-2021 Steinar Bang
+ * Copyright 2019-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,46 +15,26 @@
*/
package no.priv.bang.ukelonn.beans;
-public class SumYear {
+public record SumYear(double sum, int year) {
- private double sum;
- private int year;
-
- protected SumYear() {}
-
- public double getSum() {
- return sum;
- }
-
- public int getYear() {
- return year;
+ public static Builder with() {
+ return new Builder();
}
- public static SumYearBuilder with() {
- return new SumYearBuilder();
- }
-
- public static class SumYearBuilder {
+ public static class Builder {
private double sum = 0.0;
private int year = -1;
public SumYear build() {
- SumYear sumYear = new SumYear();
- copyValues(sumYear);
- return sumYear;
- }
-
- protected void copyValues(SumYear sumYear) {
- sumYear.sum = this.sum;
- sumYear.year = this.year;
+ return new SumYear(sum, year);
}
- public SumYearBuilder sum(double sum) {
+ public Builder sum(double sum) {
this.sum = sum;
return this;
}
- public SumYearBuilder year(int year) {
+ public Builder year(int year) {
this.year = year;
return this;
}
diff --git a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/SumYearMonth.java b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/SumYearMonth.java
index b8b4083b..0690a942 100644
--- a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/SumYearMonth.java
+++ b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/SumYearMonth.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2019-2021 Steinar Bang
+ * Copyright 2019-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,44 +15,32 @@
*/
package no.priv.bang.ukelonn.beans;
-public class SumYearMonth extends SumYear {
+public record SumYearMonth(double sum, int year, int month) {
- private int month;
-
- private SumYearMonth() {}
-
- public int getMonth() {
- return month;
- }
-
- public static SumYearMonthBuilder with() {
- return new SumYearMonthBuilder();
+ public static Builder with() {
+ return new Builder();
}
- public static class SumYearMonthBuilder extends SumYearBuilder {
+ public static class Builder {
+ private double sum = 0.0;
+ private int year = -1;
private int month = -1;
- @Override
public SumYearMonth build() {
- SumYearMonth sumYearMonth = new SumYearMonth();
- copyValues(sumYearMonth);
- sumYearMonth.month = this.month;
- return sumYearMonth;
+ return new SumYearMonth(sum, year, month);
}
- @Override
- public SumYearMonthBuilder sum(double sum) {
- super.sum(sum);
+ public Builder sum(double sum) {
+ this.sum = sum;
return this;
}
- @Override
- public SumYearMonthBuilder year(int year) {
- super.year(year);
+ public Builder year(int year) {
+ this.year = year;
return this;
}
- public SumYearMonthBuilder month(int month) {
+ public Builder month(int month) {
this.month = month;
return this;
}
diff --git a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Transaction.java b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Transaction.java
index 669a64f8..cf984096 100644
--- a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Transaction.java
+++ b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/Transaction.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016-2021 Steinar Bang
+ * Copyright 2016-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,49 +17,16 @@
import java.util.Date;
-import no.priv.bang.beans.immutable.Immutable;
+public record Transaction(
+ int id,
+ TransactionType transactionType,
+ Date transactionTime,
+ double transactionAmount,
+ boolean paidOut)
+{
-public class Transaction extends Immutable { // NOSONAR Immutable handles added fields
- private int id;
- private TransactionType transactionType;
- private Date transactionTime;
- private double transactionAmount;
- private boolean paidOut;
-
- private Transaction() {}
-
- public int getId() {
- return id;
- }
-
- public String getName() {
- return this.transactionType.getTransactionTypeName();
- }
-
- public TransactionType getTransactionType() {
- return transactionType;
- }
-
- public Date getTransactionTime() {
- return transactionTime;
- }
-
- public double getTransactionAmount() {
- return transactionAmount;
- }
-
- public boolean isPaidOut() {
- return paidOut;
- }
-
- @Override
- public String toString() {
- return "Transaction [id=" + id + ", transactionType=" + transactionType + ", transactionTime=" + transactionTime
- + ", transactionAmount=" + transactionAmount + "]";
- }
-
- public static TransactionBuilder with(Transaction transaction) {
- TransactionBuilder builder = new TransactionBuilder();
+ public static Builder with(Transaction transaction) {
+ Builder builder = new Builder();
builder.id = transaction.id;
builder.transactionType = transaction.transactionType;
builder.transactionTime = transaction.transactionTime;
@@ -68,50 +35,44 @@ public static TransactionBuilder with(Transaction transaction) {
return builder;
}
- public static TransactionBuilder with() {
- return new TransactionBuilder();
+ public static Builder with() {
+ return new Builder();
}
- public static class TransactionBuilder {
+ public static class Builder {
private int id = -1;
private TransactionType transactionType = null;
private Date transactionTime = null;
private double transactionAmount = 0.0;
private boolean paidOut = false;
- private TransactionBuilder() {}
+ private Builder() {}
public Transaction build() {
- Transaction transaction = new Transaction();
- transaction.id = this.id;
- transaction.transactionType = this.transactionType;
- transaction.transactionTime = this.transactionTime;
- transaction.transactionAmount = this.transactionAmount;
- transaction.paidOut = this.paidOut;
- return transaction;
+ return new Transaction(id, transactionType, transactionTime, transactionAmount, paidOut);
}
- public TransactionBuilder id(int id) {
+ public Builder id(int id) {
this.id = id;
return this;
}
- public TransactionBuilder transactionType(TransactionType transactionType) {
+ public Builder transactionType(TransactionType transactionType) {
this.transactionType = transactionType;
return this;
}
- public TransactionBuilder transactionTime(Date transactionTime) {
+ public Builder transactionTime(Date transactionTime) {
this.transactionTime = transactionTime;
return this;
}
- public TransactionBuilder transactionAmount(double transactionAmount) {
+ public Builder transactionAmount(double transactionAmount) {
this.transactionAmount = transactionAmount;
return this;
}
- public TransactionBuilder paidOut(boolean paidOut) {
+ public Builder paidOut(boolean paidOut) {
this.paidOut = paidOut;
return this;
}
diff --git a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/TransactionType.java b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/TransactionType.java
index 84d24446..db404b0d 100644
--- a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/TransactionType.java
+++ b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/TransactionType.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016-2021 Steinar Bang
+ * Copyright 2016-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,46 +15,16 @@
*/
package no.priv.bang.ukelonn.beans;
-import no.priv.bang.beans.immutable.Immutable;
+public record TransactionType(
+ int id,
+ String transactionTypeName,
+ Double transactionAmount,
+ boolean transactionIsWork,
+ boolean transactionIsWagePayment)
+{
-public class TransactionType extends Immutable { // NOSONAR Immutable handles added fields
- private int id;
- private String transactionTypeName;
- private Double transactionAmount;
- private boolean transactionIsWork;
- private boolean transactionIsWagePayment;
-
- private TransactionType() {}
-
- public Integer getId() {
- return Integer.valueOf(id);
- }
-
- public String getTransactionTypeName() {
- return transactionTypeName;
- }
-
- public Double getTransactionAmount() {
- return transactionAmount;
- }
-
- public boolean isTransactionIsWork() {
- return transactionIsWork;
- }
-
- public boolean isTransactionIsWagePayment() {
- return transactionIsWagePayment;
- }
-
- @Override
- public String toString() {
- return "TransactionType [id=" + id + ", transactionTypeName=" + transactionTypeName + ", transactionAmount="
- + transactionAmount + ", transactionIsWork=" + transactionIsWork + ", transactionIsWagePayment="
- + transactionIsWagePayment + "]";
- }
-
- public static TransactionTypeBuilder with(TransactionType transactiontype) {
- TransactionTypeBuilder builder = new TransactionTypeBuilder();
+ public static Builder with(TransactionType transactiontype) {
+ Builder builder = new Builder();
builder.id = transactiontype.id;
builder.transactionTypeName = transactiontype.transactionTypeName;
builder.transactionAmount = transactiontype.transactionAmount;
@@ -63,50 +33,44 @@ public static TransactionTypeBuilder with(TransactionType transactiontype) {
return builder;
}
- public static TransactionTypeBuilder with() {
- return new TransactionTypeBuilder();
+ public static Builder with() {
+ return new Builder();
}
- public static class TransactionTypeBuilder {
+ public static class Builder {
private int id;
private String transactionTypeName;
private Double transactionAmount;
private boolean transactionIsWork;
private boolean transactionIsWagePayment;
- private TransactionTypeBuilder() {}
+ private Builder() {}
public TransactionType build() {
- TransactionType transactionType = new TransactionType();
- transactionType.id = this.id;
- transactionType.transactionTypeName = this.transactionTypeName;
- transactionType.transactionAmount = this.transactionAmount;
- transactionType.transactionIsWork = this.transactionIsWork;
- transactionType.transactionIsWagePayment = this.transactionIsWagePayment;
- return transactionType;
+ return new TransactionType(id, transactionTypeName, transactionAmount, transactionIsWork, transactionIsWagePayment);
}
- public TransactionTypeBuilder id(int id) {
+ public Builder id(int id) {
this.id = id;
return this;
}
- public TransactionTypeBuilder transactionTypeName(String transactionTypeName) {
+ public Builder transactionTypeName(String transactionTypeName) {
this.transactionTypeName = transactionTypeName;
return this;
}
- public TransactionTypeBuilder transactionAmount(Double transactionAmount) {
+ public Builder transactionAmount(Double transactionAmount) {
this.transactionAmount = transactionAmount;
return this;
}
- public TransactionTypeBuilder transactionIsWork(boolean transactionIsWork) {
+ public Builder transactionIsWork(boolean transactionIsWork) {
this.transactionIsWork = transactionIsWork;
return this;
}
- public TransactionTypeBuilder transactionIsWagePayment(boolean transactionIsWagePayment) {
+ public Builder transactionIsWagePayment(boolean transactionIsWagePayment) {
this.transactionIsWagePayment = transactionIsWagePayment;
return this;
}
diff --git a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/UpdatedTransaction.java b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/UpdatedTransaction.java
index 20c29278..7be8eb32 100644
--- a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/UpdatedTransaction.java
+++ b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/UpdatedTransaction.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2018-2021 Steinar Bang
+ * Copyright 2018-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,80 +20,52 @@
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown=true)
-public class UpdatedTransaction {
-
- private int id;
- private int accountId;
- private int transactionTypeId;
- private Date transactionTime;
- private double transactionAmount;
-
- private UpdatedTransaction() {}
-
- public int getId() {
- return id;
- }
-
- public int getAccountId() {
- return accountId;
- }
-
- public int getTransactionTypeId() {
- return transactionTypeId;
- }
-
- public Date getTransactionTime() {
- return transactionTime;
- }
-
- public double getTransactionAmount() {
- return transactionAmount;
- }
-
- public static UpdatedTransactionBuilder with() {
- return new UpdatedTransactionBuilder();
+public record UpdatedTransaction(
+ int id,
+ int accountId,
+ int transactionTypeId,
+ Date transactionTime,
+ double transactionAmount)
+{
+
+ public static Builder with() {
+ return new Builder();
}
- public static class UpdatedTransactionBuilder {
+ public static class Builder {
private int id = -1;
private int accountId = -1;
private int transactionTypeId = -1;
private Date transactionTime = null;
private double transactionAmount = 0.0;
- private UpdatedTransactionBuilder() {}
+ private Builder() {}
public UpdatedTransaction build() {
- UpdatedTransaction updatedTransaction = new UpdatedTransaction();
- updatedTransaction.id = this.id;
- updatedTransaction.accountId = this.accountId;
- updatedTransaction.transactionTypeId = this.transactionTypeId;
- updatedTransaction.transactionTime = this.transactionTime;
- updatedTransaction.transactionAmount = this.transactionAmount;
- return updatedTransaction;
+ return new UpdatedTransaction(id, accountId, transactionTypeId, transactionTime, transactionAmount);
}
- public UpdatedTransactionBuilder id(int id) {
+ public Builder id(int id) {
this.id = id;
return this;
}
- public UpdatedTransactionBuilder accountId(int accountId) {
+ public Builder accountId(int accountId) {
this.accountId = accountId;
return this;
}
- public UpdatedTransactionBuilder transactionTypeId(int transactionTypeId) {
+ public Builder transactionTypeId(int transactionTypeId) {
this.transactionTypeId = transactionTypeId;
return this;
}
- public UpdatedTransactionBuilder transactionTime(Date transactionTime) {
+ public Builder transactionTime(Date transactionTime) {
this.transactionTime = transactionTime;
return this;
}
- public UpdatedTransactionBuilder transactionAmount(double transactionAmount) {
+ public Builder transactionAmount(double transactionAmount) {
this.transactionAmount = transactionAmount;
return this;
}
diff --git a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/User.java b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/User.java
index 1513a2f2..01393745 100644
--- a/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/User.java
+++ b/ukelonn.services/src/main/java/no/priv/bang/ukelonn/beans/User.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016-2021 Steinar Bang
+ * Copyright 2016-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,53 +17,19 @@
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-import no.priv.bang.beans.immutable.Immutable;
-
@JsonIgnoreProperties(ignoreUnknown=true)
-public class User extends Immutable { // NOSONAR Immutable handles added fields
- private int userId;
- private String username;
- private String email;
- private String firstname;
- private String lastname;
-
- private User() {}
-
- public int getUserId() {
- return userId;
- }
-
- public String getUsername() {
- return username;
- }
-
- public String getEmail() {
- return email;
- }
-
- public String getFirstname() {
- return firstname;
- }
-
- public String getLastname() {
- return lastname;
- }
-
- public String getFullname() {
- return new StringBuilder(getFirstname()).append(" ").append(getLastname()).toString();
- }
+public record User(int userId, String username, String email, String firstname, String lastname) {
- @Override
- public String toString() {
- return "User [userId=" + userId + ", username=" + username + ", email=" + email + ", firstname=" + firstname + ", lastname=" + lastname + "]";
+ public String fullname() {
+ return new StringBuilder(firstname()).append(" ").append(lastname()).toString();
}
- public static UserBuilder with() {
- return new UserBuilder();
+ public static Builder with() {
+ return new Builder();
}
- public static UserBuilder with(User user) {
- UserBuilder builder = new UserBuilder();
+ public static Builder with(User user) {
+ Builder builder = new Builder();
builder.userId = user.userId;
builder.username = user.username;
builder.email = user.email;
@@ -72,46 +38,40 @@ public static UserBuilder with(User user) {
return builder;
}
- public static class UserBuilder {
+ public static class Builder {
private int userId = -1;
private String username = "";
private String email = "";
private String firstname = "";
private String lastname = "";
- private UserBuilder() {}
+ private Builder() {}
public User build() {
- User user = new User();
- user.userId = this.userId;
- user.username = this.username;
- user.email = this.email;
- user.firstname = this.firstname;
- user.lastname = this.lastname;
- return user;
+ return new User(userId, username, email, firstname, lastname);
}
- public UserBuilder userId(int userId) {
+ public Builder userId(int userId) {
this.userId = userId;
return this;
}
- public UserBuilder username(String username) {
+ public Builder username(String username) {
this.username = username;
return this;
}
- public UserBuilder email(String email) {
+ public Builder email(String email) {
this.email = email;
return this;
}
- public UserBuilder firstname(String firstname) {
+ public Builder firstname(String firstname) {
this.firstname = firstname;
return this;
}
- public UserBuilder lastname(String lastname) {
+ public Builder lastname(String lastname) {
this.lastname = lastname;
return this;
}
diff --git a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/AccountTest.java b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/AccountTest.java
index 7d768319..2179af62 100644
--- a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/AccountTest.java
+++ b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/AccountTest.java
@@ -36,15 +36,12 @@ void testProperties() {
.balance(expectedBalance)
.build();
- assertEquals(expectedAccountId, account.getAccountId());
- assertEquals(expectedUsername, account.getUsername());
- assertEquals(expectedFirstname, account.getFirstName());
- assertEquals(expectedLastname, account.getLastName());
- assertEquals(expectedBalance, account.getBalance(), 0.0);
+ assertEquals(expectedAccountId, account.accountId());
+ assertEquals(expectedUsername, account.username());
+ assertEquals(expectedFirstname, account.firstName());
+ assertEquals(expectedLastname, account.lastName());
+ assertEquals(expectedBalance, account.balance(), 0.0);
assertEquals("Jane Doe", account.getFullName());
-
- account.setBalance(2);
- assertEquals(2.0, account.getBalance(), 0.0);
}
@Test
@@ -77,12 +74,4 @@ void testFullNameWhenNoFirstName() {
assertEquals("jad", account.getFullName());
}
- @Test
- void testToString() {
- var account = Account.with().accountid(1).username("jad").firstName("Jane").lastName("Doe").balance(1).build();
- assertEquals("Account [getAccountId()=1, getUsername()=jad, getFirstName()=Jane, getLastName()=Doe]", account.toString());
- var accountWithNullStrings = Account.with().accountid(1).build();
- assertEquals("Account [getAccountId()=1, getUsername()=null, getFirstName()=null, getLastName()=null]", accountWithNullStrings.toString());
- }
-
}
diff --git a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/AccountWithJobIdsTest.java b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/AccountWithJobIdsTest.java
index bf7d82b4..1ed1aee5 100644
--- a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/AccountWithJobIdsTest.java
+++ b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/AccountWithJobIdsTest.java
@@ -25,8 +25,8 @@ class AccountWithJobIdsTest {
@Test
void testDefaultValues() {
var bean = AccountWithJobIds.with().build();
- assertNull(bean.getAccount());
- assertEquals(0, bean.getJobIds().size());
+ assertNull(bean.account());
+ assertEquals(0, bean.jobIds().size());
}
@Test
@@ -34,8 +34,8 @@ void testConstructorWithParameters() {
var account = Account.with().build();
var ids = Arrays.asList(1, 2, 3, 4);
var bean = AccountWithJobIds.with().account(account).jobIds(ids).build();
- assertEquals(account, bean.getAccount());
- assertEquals(4, bean.getJobIds().size());
+ assertEquals(account, bean.account());
+ assertEquals(4, bean.jobIds().size());
}
}
diff --git a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/BonusTest.java b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/BonusTest.java
index 9175bf14..9bfb8279 100644
--- a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/BonusTest.java
+++ b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/BonusTest.java
@@ -43,27 +43,27 @@ void testCreate() {
.startDate(startDate)
.endDate(endDate)
.build();
- assertEquals(bonusId, bean.getBonusId());
- assertTrue(bean.isEnabled());
- assertEquals(iconurl, bean.getIconurl());
- assertEquals(title, bean.getTitle());
- assertEquals(description, bean.getDescription());
- assertEquals(bonusFactor, bean.getBonusFactor(), 0.0);
- assertEquals(startDate, bean.getStartDate());
- assertEquals(endDate, bean.getEndDate());
+ assertEquals(bonusId, bean.bonusId());
+ assertTrue(bean.enabled());
+ assertEquals(iconurl, bean.iconurl());
+ assertEquals(title, bean.title());
+ assertEquals(description, bean.description());
+ assertEquals(bonusFactor, bean.bonusFactor(), 0.0);
+ assertEquals(startDate, bean.startDate());
+ assertEquals(endDate, bean.endDate());
}
@Test
void testNoArgsConstructor() {
var bean = Bonus.with().build();
- assertEquals(0, bean.getBonusId());
- assertFalse(bean.isEnabled());
- assertNull(bean.getIconurl());
- assertNull(bean.getTitle());
- assertNull(bean.getDescription());
- assertEquals(0.0, bean.getBonusFactor(), 0.0);
- assertNull(bean.getStartDate());
- assertNull(bean.getEndDate());
+ assertEquals(0, bean.bonusId());
+ assertFalse(bean.enabled());
+ assertNull(bean.iconurl());
+ assertNull(bean.title());
+ assertNull(bean.description());
+ assertEquals(0.0, bean.bonusFactor(), 0.0);
+ assertNull(bean.startDate());
+ assertNull(bean.endDate());
}
}
diff --git a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/LocaleBeanTest.java b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/LocaleBeanTest.java
index 23bc72ad..c709d364 100644
--- a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/LocaleBeanTest.java
+++ b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/LocaleBeanTest.java
@@ -26,23 +26,23 @@ class LocaleBeanTest {
@Test
void testUK() {
var bean = LocaleBean.with().locale(Locale.UK).build();
- assertEquals("en_GB", bean.getCode());
- assertEquals("English", bean.getDisplayLanguage());
+ assertEquals("en_GB", bean.code());
+ assertEquals("English", bean.displayLanguage());
}
@Test
void testNO() {
var norsk = Locale.forLanguageTag("nb-NO");
var bean = LocaleBean.with().locale(norsk).build();
- assertEquals("nb_NO", bean.getCode());
- assertEquals(norsk.getDisplayLanguage(norsk), bean.getDisplayLanguage());
+ assertEquals("nb_NO", bean.code());
+ assertEquals(norsk.getDisplayLanguage(norsk), bean.displayLanguage());
}
@Test
void testNoArgsConstructor() {
var bean = LocaleBean.with().build();
- assertNull(bean.getCode());
- assertNull(bean.getDisplayLanguage());
+ assertNull(bean.code());
+ assertNull(bean.displayLanguage());
}
}
diff --git a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/NotificationTest.java b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/NotificationTest.java
index 3bf08148..dd75297b 100644
--- a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/NotificationTest.java
+++ b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/NotificationTest.java
@@ -24,15 +24,15 @@ class NotificationTest {
@Test
void testGetters() {
var bean = Notification.with().title("UkelĂžnn").message("150 kroner utbetalt til konto").build();
- assertEquals("UkelĂžnn", bean.getTitle());
- assertEquals("150 kroner utbetalt til konto", bean.getMessage());
+ assertEquals("UkelĂžnn", bean.title());
+ assertEquals("150 kroner utbetalt til konto", bean.message());
}
@Test
void testNoArgsConstructor() {
var bean = Notification.with().build();
- assertEquals("", bean.getTitle());
- assertEquals("", bean.getMessage());
+ assertEquals("", bean.title());
+ assertEquals("", bean.message());
}
}
diff --git a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/PasswordsWithUserTest.java b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/PasswordsWithUserTest.java
index ac904230..003fb754 100644
--- a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/PasswordsWithUserTest.java
+++ b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/PasswordsWithUserTest.java
@@ -38,12 +38,12 @@ void testProperties() {
var password = "zecret";
var password2 = "zecret2";
var passwords = PasswordsWithUser.with().user(user).password(password).password2(password2).build();
- assertEquals("jad", passwords.getUser().getUsername());
- assertEquals(password, passwords.getPassword());
- assertEquals(password2, passwords.getPassword2());
+ assertEquals("jad", passwords.user().username());
+ assertEquals(password, passwords.password());
+ assertEquals(password2, passwords.password2());
var user2 = User.with().build();
- passwords.setUser(user2);
- assertEquals(user2, passwords.getUser());
+ passwords = PasswordsWithUser.with(passwords).user(user2).build();
+ assertEquals(user2, passwords.user());
}
}
diff --git a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/PerformedTransactionTest.java b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/PerformedTransactionTest.java
index 926c76a2..2a32bb08 100644
--- a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/PerformedTransactionTest.java
+++ b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/PerformedTransactionTest.java
@@ -26,9 +26,9 @@ class PerformedTransactionTest {
@Test
void testNoArgsConstructor() {
var bean = PerformedTransaction.with().build();
- assertNull(bean.getAccount());
- assertEquals(-1, bean.getTransactionTypeId());
- assertEquals(0.0, bean.getTransactionAmount(), 0.0);
+ assertNull(bean.account());
+ assertEquals(-1, bean.transactionTypeId());
+ assertEquals(0.0, bean.transactionAmount(), 0.0);
}
@Test
@@ -41,10 +41,10 @@ void testConstructorWithArgs() {
.transactionAmount(3.14)
.transactionDate(now)
.build();
- assertEquals(account, bean.getAccount());
- assertEquals(1, bean.getTransactionTypeId());
- assertEquals(3.14, bean.getTransactionAmount(), 0.0);
- assertEquals(now, bean.getTransactionDate());
+ assertEquals(account, bean.account());
+ assertEquals(1, bean.transactionTypeId());
+ assertEquals(3.14, bean.transactionAmount(), 0.0);
+ assertEquals(now, bean.transactionDate());
}
}
diff --git a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/SumYearMonthTest.java b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/SumYearMonthTest.java
index b3917432..69537a98 100644
--- a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/SumYearMonthTest.java
+++ b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/SumYearMonthTest.java
@@ -27,9 +27,9 @@ void test() {
var year = 2016;
var month = 11;
var bean = SumYearMonth.with().sum(sum).year(year).month(month).build();
- assertEquals(sum, bean.getSum(), 0.0);
- assertEquals(year, bean.getYear());
- assertEquals(month, bean.getMonth());
+ assertEquals(sum, bean.sum(), 0.0);
+ assertEquals(year, bean.year());
+ assertEquals(month, bean.month());
}
@Test
@@ -38,9 +38,9 @@ void testNoArgsConstructor() {
var year = -1;
var month = -1;
var bean = SumYearMonth.with().build();
- assertEquals(sum, bean.getSum(), 0.0);
- assertEquals(year, bean.getYear());
- assertEquals(month, bean.getMonth());
+ assertEquals(sum, bean.sum(), 0.0);
+ assertEquals(year, bean.year());
+ assertEquals(month, bean.month());
}
}
diff --git a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/SumYearTest.java b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/SumYearTest.java
index 8928daeb..bc9bc0b4 100644
--- a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/SumYearTest.java
+++ b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/SumYearTest.java
@@ -26,8 +26,8 @@ void testBean() {
var sum = 250.0;
var year = 2016;
var bean = SumYear.with().sum(sum).year(year).build();
- assertEquals(sum, bean.getSum(), 0.0);
- assertEquals(year, bean.getYear());
+ assertEquals(sum, bean.sum(), 0.0);
+ assertEquals(year, bean.year());
}
@Test
@@ -35,8 +35,8 @@ void testNoArgsConstructor() {
var sum = 0.0;
var year = -1;
var bean = SumYear.with().build();
- assertEquals(sum, bean.getSum(), 0.0);
- assertEquals(year, bean.getYear());
+ assertEquals(sum, bean.sum(), 0.0);
+ assertEquals(year, bean.year());
}
}
diff --git a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/TransactionTest.java b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/TransactionTest.java
index 877c1a46..5e51a959 100644
--- a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/TransactionTest.java
+++ b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/TransactionTest.java
@@ -24,11 +24,11 @@ class TransactionTest {
@Test
void testNoArgConstructor() {
var bean = Transaction.with().build();
- assertEquals(-1, bean.getId());
- assertNull(bean.getTransactionType());
- assertNull(bean.getTransactionTime());
- assertEquals(0.0, bean.getTransactionAmount(), 0.0);
- assertFalse(bean.isPaidOut());
+ assertEquals(-1, bean.id());
+ assertNull(bean.transactionType());
+ assertNull(bean.transactionTime());
+ assertEquals(0.0, bean.transactionAmount(), 0.0);
+ assertFalse(bean.paidOut());
}
@Test
@@ -45,11 +45,11 @@ void testConstructorWithArgs() {
.transactionAmount(transactionAmount)
.paidOut(paidOut)
.build();
- assertEquals(id, bean.getId());
- assertEquals(transactionType, bean.getTransactionType());
- assertEquals(transactionTime, bean.getTransactionTime());
- assertEquals(transactionAmount, bean.getTransactionAmount(), 0.0);
- assertTrue(bean.isPaidOut());
+ assertEquals(id, bean.id());
+ assertEquals(transactionType, bean.transactionType());
+ assertEquals(transactionTime, bean.transactionTime());
+ assertEquals(transactionAmount, bean.transactionAmount(), 0.0);
+ assertTrue(bean.paidOut());
}
}
diff --git a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/TransactionTypeTest.java b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/TransactionTypeTest.java
index 48d0bb60..f9d8229d 100644
--- a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/TransactionTypeTest.java
+++ b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/TransactionTypeTest.java
@@ -16,8 +16,6 @@
package no.priv.bang.ukelonn.beans;
import static org.junit.jupiter.api.Assertions.*;
-import static org.assertj.core.api.Assertions.assertThat;
-
import org.junit.jupiter.api.Test;
class TransactionTypeTest {
@@ -25,11 +23,11 @@ class TransactionTypeTest {
@Test
void testNoArgumentConstructor() {
var bean = TransactionType.with().build();
- assertEquals(Integer.valueOf(0), bean.getId());
- assertNull(bean.getTransactionTypeName());
- assertNull(bean.getTransactionAmount());
- assertFalse(bean.isTransactionIsWork());
- assertFalse(bean.isTransactionIsWagePayment());
+ assertEquals(Integer.valueOf(0), bean.id());
+ assertNull(bean.transactionTypeName());
+ assertNull(bean.transactionAmount());
+ assertFalse(bean.transactionIsWork());
+ assertFalse(bean.transactionIsWagePayment());
}
@Test
@@ -40,17 +38,11 @@ void testConstructorWithArguments() {
.transactionAmount(45.0)
.transactionIsWork(true)
.build();
- assertEquals(Integer.valueOf(1), bean.getId());
- assertEquals("Vaske", bean.getTransactionTypeName());
- assertEquals(Double.valueOf(45), bean.getTransactionAmount());
- assertTrue(bean.isTransactionIsWork());
- assertFalse(bean.isTransactionIsWagePayment());
- }
-
- @Test
- void testToString() {
- var bean = TransactionType.with().id(1).transactionTypeName("Vaske").transactionAmount(45.0).transactionIsWork(true).build();
- assertThat(bean.toString()).startsWith("TransactionType [");
+ assertEquals(Integer.valueOf(1), bean.id());
+ assertEquals("Vaske", bean.transactionTypeName());
+ assertEquals(Double.valueOf(45), bean.transactionAmount());
+ assertTrue(bean.transactionIsWork());
+ assertFalse(bean.transactionIsWagePayment());
}
}
diff --git a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/UpdatedTransactionTest.java b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/UpdatedTransactionTest.java
index d88349ef..612a44c0 100644
--- a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/UpdatedTransactionTest.java
+++ b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/UpdatedTransactionTest.java
@@ -33,21 +33,21 @@ void testCreate() {
.transactionTime(now)
.transactionAmount(3.14)
.build();
- assertEquals(31, bean.getId());
- assertEquals(2, bean.getAccountId());
- assertEquals(2, bean.getTransactionTypeId());
- assertEquals(now, bean.getTransactionTime());
- assertEquals(3.14, bean.getTransactionAmount(), 0.0);
+ assertEquals(31, bean.id());
+ assertEquals(2, bean.accountId());
+ assertEquals(2, bean.transactionTypeId());
+ assertEquals(now, bean.transactionTime());
+ assertEquals(3.14, bean.transactionAmount(), 0.0);
}
@Test
void testNoArgsConstructor() {
var bean = UpdatedTransaction.with().build();
- assertEquals(-1, bean.getId());
- assertEquals(-1, bean.getTransactionTypeId());
- assertEquals(-1, bean.getTransactionTypeId());
- assertNull(bean.getTransactionTime());
- assertEquals(0.0, bean.getTransactionAmount(), 0.0);
+ assertEquals(-1, bean.id());
+ assertEquals(-1, bean.transactionTypeId());
+ assertEquals(-1, bean.transactionTypeId());
+ assertNull(bean.transactionTime());
+ assertEquals(0.0, bean.transactionAmount(), 0.0);
}
}
diff --git a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/UserTest.java b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/UserTest.java
index 0c22e2b5..dfa852e0 100644
--- a/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/UserTest.java
+++ b/ukelonn.services/src/test/java/no/priv/bang/ukelonn/beans/UserTest.java
@@ -24,12 +24,12 @@ class UserTest {
@Test
void testNoArgConstructor() {
var bean = User.with().build();
- assertEquals(-1, bean.getUserId());
- assertEquals("", bean.getUsername());
- assertEquals("", bean.getEmail());
- assertEquals("", bean.getFirstname());
- assertEquals("", bean.getLastname());
- assertEquals(" ", bean.getFullname());
+ assertEquals(-1, bean.userId());
+ assertEquals("", bean.username());
+ assertEquals("", bean.email());
+ assertEquals("", bean.firstname());
+ assertEquals("", bean.firstname());
+ assertEquals(" ", bean.fullname());
}
@Test
@@ -46,35 +46,27 @@ void testProperties() {
.firstname(expectedFirstname)
.lastname(expectedLastname)
.build();
- assertEquals(expectedUserId, user.getUserId());
- assertEquals(expectedUsername, user.getUsername());
- assertEquals(expectedEmail, user.getEmail());
- assertEquals(expectedFirstname, user.getFirstname());
- assertEquals(expectedLastname, user.getLastname());
- assertEquals("Jane Doe", user.getFullname());
+ assertEquals(expectedUserId, user.userId());
+ assertEquals(expectedUsername, user.username());
+ assertEquals(expectedEmail, user.email());
+ assertEquals(expectedFirstname, user.firstname());
+ assertEquals(expectedLastname, user.lastname());
+ assertEquals("Jane Doe", user.fullname());
var newUsername = "jadd";
var newEmail = "jane2111@gmail.com";
var newFirstname = "Juliet";
var newLastname = "Deere";
user = User.with(user).username(newUsername).build();
- assertEquals(newUsername, user.getUsername());
+ assertEquals(newUsername, user.username());
user = User.with(user).email(newEmail).build();
- assertEquals(newEmail, user.getEmail());
+ assertEquals(newEmail, user.email());
user = User.with(user).firstname(newFirstname).build();
- assertEquals(newFirstname, user.getFirstname());
- assertEquals("Juliet Doe", user.getFullname());
+ assertEquals(newFirstname, user.firstname());
+ assertEquals("Juliet Doe", user.fullname());
user = User.with(user).lastname(newLastname).build();
- assertEquals(newLastname, user.getLastname());
- assertEquals("Juliet Deere", user.getFullname());
- }
-
- @Test
- void testToString() {
- var user = User.with().userId(1).username("jad").email("jane21@gmail.com").firstname("Jane").lastname("Doe").build();
- assertEquals("User [userId=1, username=jad, email=jane21@gmail.com, firstname=Jane, lastname=Doe]", user.toString());
- var userWithNullStrings = User.with().userId(1).username(null).email(null).firstname(null).lastname(null).build();
- assertEquals("User [userId=1, username=null, email=null, firstname=null, lastname=null]", userWithNullStrings.toString());
+ assertEquals(newLastname, user.lastname());
+ assertEquals("Juliet Deere", user.fullname());
}
}
diff --git a/ukelonn.testutils/src/main/java/no/priv/bang/ukelonn/testutils/TestUtils.java b/ukelonn.testutils/src/main/java/no/priv/bang/ukelonn/testutils/TestUtils.java
index c2782784..0775a765 100644
--- a/ukelonn.testutils/src/main/java/no/priv/bang/ukelonn/testutils/TestUtils.java
+++ b/ukelonn.testutils/src/main/java/no/priv/bang/ukelonn/testutils/TestUtils.java
@@ -90,7 +90,7 @@ public class TestUtils {
private static Map transactionttypes = Collections.unmodifiableMap(
Stream.of(jobtypes, paymenttypes)
.flatMap(Collection::stream)
- .collect(Collectors.toMap(TransactionType::getId, t -> t)));
+ .collect(Collectors.toMap(TransactionType::id, t -> t)));
private static List jadJobs = Arrays.asList(
Transaction.with().id(3).transactionType(jobtype1).transactionTime(new Date()).transactionAmount(45.0).paidOut(true).build(),
Transaction.with().id(4).transactionType(jobtype2).transactionTime(new Date()).transactionAmount(35.0).paidOut(true).build(),
@@ -172,21 +172,11 @@ private static User copyUser(User user) {
private static no.priv.bang.osgiservice.users.User copyUserForUserManagement(User user) {
return no.priv.bang.osgiservice.users.User.with()
- .userid(user.getUserId())
- .username(user.getUsername())
- .email(user.getEmail())
- .firstname(user.getFirstname())
- .lastname(user.getLastname())
- .build();
- }
-
- public static Account copyAccount(Account account) {
- return Account.with()
- .accountid(account.getAccountId())
- .username(account.getUsername())
- .firstName(account.getFirstName())
- .lastName(account.getLastName())
- .balance(account.getBalance())
+ .userid(user.userId())
+ .username(user.username())
+ .email(user.email())
+ .firstname(user.firstname())
+ .lastname(user.firstname())
.build();
}
@@ -200,10 +190,10 @@ public static List copyTransactiontypes(List t
public static Transaction convertUpdatedTransaction(UpdatedTransaction transaction) {
return Transaction.with()
- .id(transaction.getId())
- .transactionType(transactionttypes.get(transaction.getTransactionTypeId()))
- .transactionTime(transaction.getTransactionTime())
- .transactionAmount(transaction.getTransactionAmount())
+ .id(transaction.id())
+ .transactionType(transactionttypes.get(transaction.transactionTypeId()))
+ .transactionTime(transaction.transactionTime())
+ .transactionAmount(transaction.transactionAmount())
.build();
}
@@ -232,11 +222,11 @@ public static List getUsersForUserManagemen
}
public static Account getJadAccount() {
- return copyAccount(jadAccount);
+ return Account.with(jadAccount).build();
}
public static Account getJodAccount() {
- return copyAccount(jodAccount);
+ return Account.with(jodAccount).build();
}
public static List getJadJobs() {
diff --git a/ukelonn.web.frontend/src/main/frontend/index.js b/ukelonn.web.frontend/src/main/frontend/index.js
index 7869fc9c..b077eada 100644
--- a/ukelonn.web.frontend/src/main/frontend/index.js
+++ b/ukelonn.web.frontend/src/main/frontend/index.js
@@ -12,6 +12,7 @@ import {
DEFAULT_LOCALE_REQUEST,
AVAILABLE_LOCALES_REQUEST,
} from './actiontypes';
+import { push } from 'redux-first-history';
import createUkelonnReducer from './reducers';
import { rootSaga } from './sagas';
const baseUrl = Array.from(document.scripts).map(s => s.src).filter(src => src.includes('bundle.js'))[0].replace('/bundle.js', '');
@@ -35,6 +36,10 @@ sagaMiddleware.run(rootSaga);
store.dispatch(INITIAL_LOGIN_STATE_REQUEST());
store.dispatch(DEFAULT_LOCALE_REQUEST());
store.dispatch(AVAILABLE_LOCALES_REQUEST());
+// Use redux to reload the current path to trigger the locationChange() saga
+const router = store.getState().router;
+const pathname = router.location.pathname;
+store.dispatch(push(pathname));
if (typeof Notification !== 'undefined') {
Notification.requestPermission().then(function(result) {
diff --git a/ukelonn.web.security/src/main/java/no/priv/bang/ukelonn/web/security/UkelonnShiroFilter.java b/ukelonn.web.security/src/main/java/no/priv/bang/ukelonn/web/security/UkelonnShiroFilter.java
index 802c02c8..d2980bcd 100644
--- a/ukelonn.web.security/src/main/java/no/priv/bang/ukelonn/web/security/UkelonnShiroFilter.java
+++ b/ukelonn.web.security/src/main/java/no/priv/bang/ukelonn/web/security/UkelonnShiroFilter.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016-2021 Steinar Bang
+ * Copyright 2016-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -65,14 +65,14 @@ public void setSession(SessionDAO session) {
@Activate
public void activate() {
- IniWebEnvironment environment = new IniWebEnvironment();
+ var environment = new IniWebEnvironment();
environment.setIni(INI_FILE);
environment.setServletContext(getServletContext());
environment.init();
- DefaultWebSessionManager sessionmanager = new DefaultWebSessionManager();
+ var sessionmanager = new DefaultWebSessionManager();
sessionmanager.setSessionDAO(session);
sessionmanager.setSessionIdUrlRewritingEnabled(false);
- DefaultWebSecurityManager securityManager = DefaultWebSecurityManager.class.cast(environment.getWebSecurityManager());
+ var securityManager = DefaultWebSecurityManager.class.cast(environment.getWebSecurityManager());
securityManager.setSessionManager(sessionmanager);
securityManager.setRealm(realm);
setSecurityManager(securityManager);
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/beans/AdminStatus.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/beans/AdminStatus.java
index cd738edf..b6ceadfc 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/beans/AdminStatus.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/beans/AdminStatus.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2020-2021 Steinar Bang
+ * Copyright 2020-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,44 +17,28 @@
import no.priv.bang.osgiservice.users.User;
-public class AdminStatus {
+public record AdminStatus(User user, boolean administrator) {
- private User user;
- private boolean administrator;
-
- private AdminStatus() {}
-
- public static AdminStatusBuilder with() {
- return new AdminStatusBuilder();
- }
-
- public User getUser() {
- return user;
- }
-
- public boolean isAdministrator() {
- return administrator;
+ public static Builder with() {
+ return new Builder();
}
- public static class AdminStatusBuilder {
+ public static class Builder {
private User user;
private boolean administrator;
- private AdminStatusBuilder() {}
+ private Builder() {}
public AdminStatus build() {
- AdminStatus adminStatus = new AdminStatus();
- adminStatus.user = this.user;
- adminStatus.administrator = this.administrator;
- return adminStatus;
+ return new AdminStatus(this.user, this.administrator);
}
- public AdminStatusBuilder user(User user) {
+ public Builder user(User user) {
this.user = user;
return this;
}
- public AdminStatusBuilder administrator(boolean administrator) {
+ public Builder administrator(boolean administrator) {
this.administrator = administrator;
return this;
}
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/beans/LoginCredentials.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/beans/LoginCredentials.java
index 34da5312..1e3fea48 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/beans/LoginCredentials.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/beans/LoginCredentials.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2018-2021 Steinar Bang
+ * Copyright 2018-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,43 +15,28 @@
*/
package no.priv.bang.ukelonn.api.beans;
-public class LoginCredentials {
- private String username;
- private String password;
+public record LoginCredentials(String username, String password) {
- private LoginCredentials() {}
-
- public static LoginCredentialsBuilder with() {
- return new LoginCredentialsBuilder();
- }
-
- public String getUsername() {
- return username;
- }
-
- public String getPassword() {
- return password;
+ public static Builder with() {
+ return new Builder();
}
- public static class LoginCredentialsBuilder {
+ public static class Builder {
private String username;
private String password;
- private LoginCredentialsBuilder() {}
+ private Builder() {}
public LoginCredentials build() {
- LoginCredentials loginCredentials = new LoginCredentials();
- loginCredentials.username = this.username;
- loginCredentials.password = this.password;
- return loginCredentials;
+ return new LoginCredentials(this.username, this.password);
}
- public LoginCredentialsBuilder username(String username) {
+ public Builder username(String username) {
this.username = username;
return this;
}
- public LoginCredentialsBuilder password(String password) {
+ public Builder password(String password) {
this.password = password;
return this;
}
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/beans/LoginResult.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/beans/LoginResult.java
index 99bd27cc..f72b6fdb 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/beans/LoginResult.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/beans/LoginResult.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2018-2021 Steinar Bang
+ * Copyright 2018-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,54 +15,33 @@
*/
package no.priv.bang.ukelonn.api.beans;
-public class LoginResult {
- private String username;
- private String[] roles;
- private String errorMessage;
+public record LoginResult(String username, String[] roles, String errorMessage) {
- private LoginResult() {}
-
- public static LoginResultBuilder with() {
- return new LoginResultBuilder();
- }
-
- public String getUsername() {
- return username;
- }
-
- public String[] getRoles() {
- return roles;
- }
-
- public String getErrorMessage() {
- return errorMessage;
+ public static Builder with() {
+ return new Builder();
}
- public static class LoginResultBuilder {
+ public static class Builder {
private String username = "";
private String[] roles = {};
private String errorMessage = "";
- private LoginResultBuilder() {}
+ private Builder() {}
public LoginResult build() {
- LoginResult loginResult = new LoginResult();
- loginResult.username = this.username;
- loginResult.roles = this.roles;
- loginResult.errorMessage = this.errorMessage;
- return loginResult;
+ return new LoginResult(this.username, this.roles, this.errorMessage);
}
- public LoginResultBuilder username(String username) {
+ public Builder username(String username) {
this.username = username;
return this;
}
- public LoginResultBuilder roles(String[] roles) {
+ public Builder roles(String[] roles) {
this.roles = roles;
return this;
}
- public LoginResultBuilder errorMessage(String errorMessage) {
+ public Builder errorMessage(String errorMessage) {
this.errorMessage = errorMessage;
return this;
}
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminJobs.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminJobs.java
index 9fe354a3..b3e20789 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminJobs.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminJobs.java
@@ -55,7 +55,7 @@ void setLogservice(LogService logservice) {
@Consumes(MediaType.APPLICATION_JSON)
public List delete(AccountWithJobIds accountWithJobIds) {
try {
- return ukelonn.deleteJobsFromAccount(accountWithJobIds.getAccount().getAccountId(), accountWithJobIds.getJobIds());
+ return ukelonn.deleteJobsFromAccount(accountWithJobIds.account().accountId(), accountWithJobIds.jobIds());
} catch (Exception e) {
String message = "REST endpoint /ukelonn/admin/jobs/delete failed with exception";
logger.error(message, e);
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminJobtype.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminJobtype.java
index 25a4867a..41bad11b 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminJobtype.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminJobtype.java
@@ -57,7 +57,7 @@ public List modify(TransactionType jobtype) {
try {
return ukelonn.modifyJobtype(jobtype);
} catch (UkelonnException e) {
- logger.error(String.format("REST endpoint /api/jobtype/modify failed to modify jobtype %d in the database", jobtype.getId()), e);
+ logger.error(String.format("REST endpoint /api/jobtype/modify failed to modify jobtype %d in the database", jobtype.id()), e);
throw new InternalServerErrorException("See log for the cause of the problem");
}
}
@@ -69,7 +69,7 @@ public List create(TransactionType jobtype) {
try {
return ukelonn.createJobtype(jobtype);
} catch (UkelonnException e) {
- logger.error(String.format("REST endpoint /api/jobtype/modify failed to create jobtype \"%s\" in the database", jobtype.getTransactionTypeName()), e);
+ logger.error(String.format("REST endpoint /api/jobtype/modify failed to create jobtype \"%s\" in the database", jobtype.transactionTypeName()), e);
throw new InternalServerErrorException("See log for the cause of the problem");
}
}
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminPaymenttype.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminPaymenttype.java
index a2b314fe..330f5c03 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminPaymenttype.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminPaymenttype.java
@@ -57,7 +57,7 @@ public List modify(TransactionType paymenttype) {
try {
return ukelonn.modifyPaymenttype(paymenttype);
} catch (UkelonnException e) {
- logger.error(String.format("REST endpoint /api/paymenttype/modify failed to modify payment type %d in the database", paymenttype.getId()), e);
+ logger.error(String.format("REST endpoint /api/paymenttype/modify failed to modify payment type %d in the database", paymenttype.id()), e);
throw new InternalServerErrorException("See log for the cause of the problem");
}
}
@@ -69,7 +69,7 @@ public List create(TransactionType paymenttype) {
try {
return ukelonn.createPaymenttype(paymenttype);
} catch (UkelonnException e) {
- logger.error(String.format("REST endpoint /api/jobtype/modify failed to create payment type \"%s\" in the database", paymenttype.getTransactionTypeName()), e);
+ logger.error(String.format("REST endpoint /api/jobtype/modify failed to create payment type \"%s\" in the database", paymenttype.transactionTypeName()), e);
throw new InternalServerErrorException("See log for the cause of the problem");
}
}
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminUserResource.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminUserResource.java
index 3d7a6d08..48a0c433 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminUserResource.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/AdminUserResource.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2018-2021 Steinar Bang
+ * Copyright 2018-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,8 +17,6 @@
import java.util.Arrays;
import java.util.List;
-import java.util.Optional;
-
import javax.inject.Inject;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
@@ -36,7 +34,6 @@
import no.priv.bang.authservice.definitions.AuthserviceException;
import no.priv.bang.authservice.definitions.AuthservicePasswordEmptyException;
import no.priv.bang.authservice.definitions.AuthservicePasswordsNotIdenticalException;
-import no.priv.bang.osgiservice.users.Role;
import no.priv.bang.osgiservice.users.User;
import no.priv.bang.osgiservice.users.UserAndPasswords;
import no.priv.bang.osgiservice.users.UserManagementService;
@@ -82,16 +79,16 @@ public List modify(User user) {
@Consumes(MediaType.APPLICATION_JSON)
public List create(UserAndPasswords passwords) {
try {
- List users = useradmin.addUser(passwords);
+ var users = useradmin.addUser(passwords);
// Create an account with a balance for the new user
- String username = passwords.getUser().getUsername();
- Optional createdUser = users.stream().filter(u -> username.equals(u.getUsername())).findFirst();
+ var username = passwords.getUser().getUsername();
+ var createdUser = users.stream().filter(u -> username.equals(u.getUsername())).findFirst();
if (!createdUser.isPresent()) {
throw new UkelonnException(String.format("Found no user matching %s in the users table", username));
}
- no.priv.bang.ukelonn.beans.User user = no.priv.bang.ukelonn.beans.User.with()
+ var user = no.priv.bang.ukelonn.beans.User.with()
.userId(createdUser.get().getUserid())
.username(username)
.email(createdUser.get().getEmail())
@@ -129,7 +126,7 @@ public List password(UserAndPasswords passwords) {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public AdminStatus adminStatus(User user) {
- boolean administrator = userIsAdministrator(user);
+ var administrator = userIsAdministrator(user);
return AdminStatus.with()
.user(user)
.administrator(administrator)
@@ -140,29 +137,29 @@ public AdminStatus adminStatus(User user) {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public AdminStatus changeAdminStatus(AdminStatus status) {
- if (status.isAdministrator() != userIsAdministrator(status.getUser())) {
- Optional ukelonnadmin = useradmin.getRoles().stream().filter(r -> UKELONNADMIN_ROLE.equals(r.getRolename())).findFirst();
+ if (status.administrator() != userIsAdministrator(status.user())) {
+ var ukelonnadmin = useradmin.getRoles().stream().filter(r -> UKELONNADMIN_ROLE.equals(r.getRolename())).findFirst();
if (!ukelonnadmin.isPresent()) {
// If no ukelonn admin role is present in the auth service
// administrator will always be false
return AdminStatus.with()
- .user(status.getUser())
+ .user(status.user())
.administrator(false)
.build();
}
- if (status.isAdministrator()) {
+ if (status.administrator()) {
// admin role is missing, add the role
- useradmin.addUserRoles(UserRoles.with().user(status.getUser()).roles(Arrays.asList(ukelonnadmin.get())).build());
+ useradmin.addUserRoles(UserRoles.with().user(status.user()).roles(Arrays.asList(ukelonnadmin.get())).build());
} else {
// admin role is present, remove the role
- useradmin.removeUserRoles(UserRoles.with().user(status.getUser()).roles(Arrays.asList(ukelonnadmin.get())).build());
+ useradmin.removeUserRoles(UserRoles.with().user(status.user()).roles(Arrays.asList(ukelonnadmin.get())).build());
}
}
return AdminStatus.with()
- .user(status.getUser())
- .administrator(userIsAdministrator(status.getUser()))
+ .user(status.user())
+ .administrator(userIsAdministrator(status.user()))
.build();
}
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/ErrorMessage.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/ErrorMessage.java
index 1bb68eda..a4468fc7 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/ErrorMessage.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/ErrorMessage.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Steinar Bang
+ * Copyright 2020-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,25 +15,5 @@
*/
package no.priv.bang.ukelonn.api.resources;
-public class ErrorMessage {
- private int status;
- private String message;
-
- public ErrorMessage(int status, String message) {
- this.status = status;
- this.message = message;
- }
-
- ErrorMessage() {
- // No-args constructor required by jackson
- }
-
- public int getStatus() {
- return status;
- }
-
- public String getMessage() {
- return message;
- }
-
+public record ErrorMessage(int status, String message) {
}
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/JobResource.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/JobResource.java
index 000fddbe..c2463628 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/JobResource.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/JobResource.java
@@ -59,7 +59,7 @@ void setLogservice(LogService logservice) {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Account doRegisterJob(PerformedTransaction performedJob) {
- String username = performedJob.getAccount().getUsername();
+ var username = performedJob.account().username();
if (!isCurrentUserOrAdmin(username, logservice)) {
logger.warn(String.format("REST Endpoint /ukelonn/api/account logged in user not allowed to fetch account for username %s", username));
throw new ForbiddenException();
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/LocalizationResource.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/LocalizationResource.java
index 30660907..3f81b2a9 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/LocalizationResource.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/LocalizationResource.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2020-2021 Steinar Bang
+ * Copyright 2020-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -68,7 +68,7 @@ public Map displayTexts(@QueryParam("locale")String locale) {
try {
return ukelonn.displayTexts(Locale.forLanguageTag(locale.replace('_', '-')));
} catch (MissingResourceException e) {
- String message = String.format("Unknown locale '%s' used when fetching GUI texts", locale);
+ var message = String.format("Unknown locale '%s' used when fetching GUI texts", locale);
logger.error(message);
throw new WebApplicationException(response(500, message));
}
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/Login.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/Login.java
index e05bc301..5a6b2af0 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/Login.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/Login.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2018-2021 Steinar Bang
+ * Copyright 2018-2024 Steinar Bang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,17 +51,17 @@ void setLogservice(LogService logservice) {
@GET
public LoginResult loginStatus() {
- Subject subject = SecurityUtils.getSubject();
+ var subject = SecurityUtils.getSubject();
return createLoginResultFromSubject(subject);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public LoginResult doLogin(LoginCredentials credentials) {
- Subject subject = SecurityUtils.getSubject();
- var decodedPassword = new String(Base64.getDecoder().decode(credentials.getPassword()));
+ var subject = SecurityUtils.getSubject();
+ var decodedPassword = new String(Base64.getDecoder().decode(credentials.password()));
- UsernamePasswordToken token = new UsernamePasswordToken(credentials.getUsername(), decodedPassword, true);
+ var token = new UsernamePasswordToken(credentials.username(), decodedPassword, true);
try {
subject.login(token);
@@ -101,7 +101,7 @@ private LoginResult createLoginResultFromSubject(Subject subject) {
roles = new String[]{ "ukelonnadmin" };
}
- String username = (String) subject.getPrincipal();
+ var username = (String) subject.getPrincipal();
return LoginResult.with()
.username(username)
.roles(roles)
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/Logout.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/Logout.java
index 1f499269..96756e25 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/Logout.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/Logout.java
@@ -23,7 +23,6 @@
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresUser;
-import org.apache.shiro.subject.Subject;
import org.osgi.service.log.LogService;
import no.priv.bang.ukelonn.api.beans.LoginResult;
@@ -38,7 +37,7 @@ public class Logout {
@POST
public LoginResult doLogout() {
- Subject subject = SecurityUtils.getSubject();
+ var subject = SecurityUtils.getSubject();
subject.logout();
return LoginResult.with().build();
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/NotificationResource.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/NotificationResource.java
index 691f8d75..56584cda 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/NotificationResource.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/NotificationResource.java
@@ -26,7 +26,6 @@
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
-import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import no.priv.bang.ukelonn.UkelonnService;
@@ -35,7 +34,6 @@
@Path("")
@Produces(MediaType.APPLICATION_JSON)
@RequiresUser
-@RequiresRoles("ukelonnadmin")
public class NotificationResource {
@Inject
diff --git a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/ResourceBase.java b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/ResourceBase.java
index a218626c..1ac505e1 100644
--- a/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/ResourceBase.java
+++ b/ukelonn.web.services/src/main/java/no/priv/bang/ukelonn/api/resources/ResourceBase.java
@@ -34,13 +34,13 @@ protected boolean isCurrentUserOrAdmin(String username, LogService logservice) {
var logger = logservice.getLogger(getClass());
try {
var subject = Optional.ofNullable(SecurityUtils.getSubject());
- boolean isCurrentUser = subject
+ var isCurrentUser = subject
.map(s -> (String)s.getPrincipal())
.map(principal -> principal.equals(username))
.orElse(false);
return subject.map(s -> s.hasRole("ukelonnadmin") || isCurrentUser).orElse(false);
} catch (Exception e) {
- String message = "Failure retrieving Shiro subject";
+ var message = "Failure retrieving Shiro subject";
logger.error(message, e);
throw new InternalServerErrorException(message);
}
diff --git a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/UkelonnRestApiServletTest.java b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/UkelonnRestApiServletTest.java
index 28c42212..81337777 100644
--- a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/UkelonnRestApiServletTest.java
+++ b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/UkelonnRestApiServletTest.java
@@ -128,8 +128,8 @@ void testLoginOk() throws Exception {
assertEquals("application/json", response.getContentType());
LoginResult result = ServletTestBase.mapper.readValue(response.getOutputStreamContent(), LoginResult.class);
- assertThat(result.getRoles()).isNotEmpty();
- assertEquals("", result.getErrorMessage());
+ assertThat(result.roles()).isNotEmpty();
+ assertEquals("", result.errorMessage());
}
@Test
@@ -163,8 +163,8 @@ void testAdminLoginOk() throws Exception {
assertEquals("application/json", response.getContentType());
var result = ServletTestBase.mapper.readValue(response.getOutputStreamContent(), LoginResult.class);
- assertThat(result.getRoles()).isNotEmpty();
- assertEquals("", result.getErrorMessage());
+ assertThat(result.roles()).isNotEmpty();
+ assertEquals("", result.errorMessage());
}
@Disabled("Gets wrong password exception instead of unknown user exception, don't know why")
@@ -196,8 +196,8 @@ void testLoginUnknownUser() throws Exception {
assertEquals("application/json", response.getContentType());
var result = ServletTestBase.mapper.readValue(response.getOutputStreamContent(), LoginResult.class);
- assertEquals(0, result.getRoles().length);
- assertEquals("Unknown account", result.getErrorMessage());
+ assertEquals(0, result.roles().length);
+ assertEquals("Unknown account", result.errorMessage());
}
@Test
@@ -231,8 +231,8 @@ void testLoginWrongPassword() throws Exception {
assertEquals("application/json", response.getContentType());
var result = ServletTestBase.mapper.readValue(response.getOutputStreamContent(), LoginResult.class);
- assertEquals(0, result.getRoles().length);
- assertEquals("Wrong password", result.getErrorMessage());
+ assertEquals(0, result.roles().length);
+ assertEquals("Wrong password", result.errorMessage());
}
@Test
@@ -296,8 +296,8 @@ void testGetLoginStateWhenLoggedIn() throws Exception {
assertEquals("application/json", response.getContentType());
LoginResult result = ServletTestBase.mapper.readValue(response.getOutputStreamContent(), LoginResult.class);
- assertThat(result.getRoles()).isNotEmpty();
- assertEquals("", result.getErrorMessage());
+ assertThat(result.roles()).isNotEmpty();
+ assertEquals("", result.errorMessage());
}
/**
@@ -336,8 +336,8 @@ void testGetLoginStateWhenNotLoggedIn() throws Exception {
assertEquals("application/json", response.getContentType());
var result = ServletTestBase.mapper.readValue(response.getOutputStreamContent(), LoginResult.class);
- assertEquals(0, result.getRoles().length);
- assertEquals("", result.getErrorMessage());
+ assertEquals(0, result.roles().length);
+ assertEquals("", result.errorMessage());
}
@Test
@@ -366,8 +366,8 @@ void testLogoutOk() throws Exception {
assertEquals("application/json", response.getContentType());
var result = ServletTestBase.mapper.readValue(response.getOutputStreamContent(), LoginResult.class);
- assertEquals(0, result.getRoles().length);
- assertEquals("", result.getErrorMessage());
+ assertEquals(0, result.roles().length);
+ assertEquals("", result.errorMessage());
}
/**
@@ -401,8 +401,8 @@ void testLogoutNotLoggedIn() throws Exception {
assertEquals("application/json", response.getContentType());
var result = ServletTestBase.mapper.readValue(response.getOutputStreamContent(), LoginResult.class);
- assertEquals(0, result.getRoles().length);
- assertEquals("", result.getErrorMessage());
+ assertEquals(0, result.roles().length);
+ assertEquals("", result.errorMessage());
}
@Test
@@ -491,10 +491,10 @@ void testGetAccount() throws Exception {
assertEquals(200, response.getStatus());
assertEquals("application/json", response.getContentType());
- var expectedAccountBalance = getJadAccount().getBalance();
+ var expectedAccountBalance = getJadAccount().balance();
var result = ServletTestBase.mapper.readValue(getBinaryContent(response), Account.class);
- assertEquals("jad", result.getUsername());
- assertEquals(expectedAccountBalance, result.getBalance(), 0.0);
+ assertEquals("jad", result.username());
+ assertEquals(expectedAccountBalance, result.balance(), 0.0);
}
/**
@@ -560,10 +560,10 @@ void testGetAccountWhenLoggedInAsAdministrator() throws Exception {
assertEquals(200, response.getStatus());
assertEquals("application/json", response.getContentType());
- var expectedAccountBalance = getJadAccount().getBalance();
+ var expectedAccountBalance = getJadAccount().balance();
var result = ServletTestBase.mapper.readValue(response.getOutputStreamContent(), Account.class);
- assertEquals("jad", result.getUsername());
- assertEquals(expectedAccountBalance, result.getBalance(), 0.0);
+ assertEquals("jad", result.username());
+ assertEquals(expectedAccountBalance, result.balance(), 0.0);
}
@Test
@@ -625,15 +625,15 @@ void testGetAccountUsernameNotPresentInDatabase() throws Exception {
void testRegisterJob() throws Exception {
// Create the request
var account = getJadAccount();
- var originalBalance = account.getBalance();
+ var originalBalance = account.balance();
var jobTypes = getJobtypes();
var job = PerformedTransaction.with()
.account(account)
- .transactionTypeId(jobTypes.get(0).getId())
- .transactionAmount(jobTypes.get(0).getTransactionAmount())
+ .transactionTypeId(jobTypes.get(0).id())
+ .transactionAmount(jobTypes.get(0).transactionAmount())
.transactionDate(new Date())
.build();
- account.setBalance(account.getBalance() + jobTypes.get(0).getTransactionAmount());
+ account = Account.with(account).balance(account.balance() + jobTypes.get(0).transactionAmount()).build();
var jobAsJson = mapper.writeValueAsString(job);
var request = buildPostUrl("/job/register");
request.setBodyContent(jobAsJson);
@@ -660,8 +660,8 @@ void testRegisterJob() throws Exception {
assertEquals("application/json", response.getContentType());
var result = ServletTestBase.mapper.readValue(response.getOutputStreamContent(), Account.class);
- assertEquals("jad", result.getUsername());
- assertThat(result.getBalance()).isGreaterThan(originalBalance);
+ assertEquals("jad", result.username());
+ assertThat(result.balance()).isGreaterThan(originalBalance);
}
/**
@@ -677,8 +677,8 @@ void testRegisterJobOtherUsername() throws Exception {
var jobTypes = getJobtypes();
var job = PerformedTransaction.with()
.account(account)
- .transactionTypeId(jobTypes.get(0).getId())
- .transactionAmount(jobTypes.get(0).getTransactionAmount())
+ .transactionTypeId(jobTypes.get(0).id())
+ .transactionAmount(jobTypes.get(0).transactionAmount())
.transactionDate(new Date())
.build();
var jobAsJson = ServletTestBase.mapper.writeValueAsString(job);
@@ -715,15 +715,15 @@ void testRegisterJobOtherUsername() throws Exception {
void testRegisterJobtWhenLoggedInAsAdministrator() throws Exception {
// Create the request
var account = getJadAccount();
- var originalBalance = account.getBalance();
+ var originalBalance = account.balance();
var jobTypes = getJobtypes();
var job = PerformedTransaction.with()
.account(account)
- .transactionTypeId(jobTypes.get(0).getId())
- .transactionAmount(jobTypes.get(0).getTransactionAmount())
+ .transactionTypeId(jobTypes.get(0).id())
+ .transactionAmount(jobTypes.get(0).transactionAmount())
.transactionDate(new Date())
.build();
- account.setBalance(account.getBalance() + jobTypes.get(0).getTransactionAmount());
+ account = Account.with(account).balance(account.balance() + jobTypes.get(0).transactionAmount()).build();
var jobAsJson = ServletTestBase.mapper.writeValueAsString(job);
var request = buildPostUrl("/job/register");
request.setBodyContent(jobAsJson);
@@ -750,8 +750,8 @@ void testRegisterJobtWhenLoggedInAsAdministrator() throws Exception {
assertEquals("application/json", response.getContentType());
var result = ServletTestBase.mapper.readValue(response.getOutputStreamContent(), Account.class);
- assertEquals("jad", result.getUsername());
- assertThat(result.getBalance()).isGreaterThan(originalBalance);
+ assertEquals("jad", result.username());
+ assertThat(result.balance()).isGreaterThan(originalBalance);
}
@Test
@@ -761,8 +761,8 @@ void testRegisterJobNoUsername() throws Exception {
var jobTypes = getJobtypes();
var job = PerformedTransaction.with()
.account(account)
- .transactionTypeId(jobTypes.get(0).getId())
- .transactionAmount(jobTypes.get(0).getTransactionAmount())
+ .transactionTypeId(jobTypes.get(0).id())
+ .transactionAmount(jobTypes.get(0).transactionAmount())
.transactionDate(new Date())
.build();
var jobAsJson = ServletTestBase.mapper.writeValueAsString(job);
@@ -819,7 +819,7 @@ void testRegisterJobUnparsablePostData() throws Exception {
void testGetJobs() throws Exception {
// Set up the request
var account = getJadAccount();
- var request = buildGetUrl(String.format("/jobs/%d", account.getAccountId()));
+ var request = buildGetUrl(String.format("/jobs/%d", account.accountId()));
// Create a response object that will receive and hold the servlet output
var response = new MockHttpServletResponse();
@@ -851,7 +851,7 @@ void testDeleteJobs() throws Exception {
// Set up the request
var account = getJodAccount();
var jobs = getJodJobs();
- var jobIds = Arrays.asList(jobs.get(0).getId(), jobs.get(1).getId());
+ var jobIds = Arrays.asList(jobs.get(0).id(), jobs.get(1).id());
var accountWithJobIds = AccountWithJobIds.with().account(account).jobIds(jobIds).build();
var accountWithJobIdsAsJson = ServletTestBase.mapper.writeValueAsString(accountWithJobIds);
var request = buildPostUrl("/admin/jobs/delete");
@@ -885,8 +885,8 @@ void testUpdateJob() throws Exception {
// Find the job that is to be modified
var account = getJodAccount();
var job = getJodJobs().get(0);
- var originalTransactionTypeId = job.getTransactionType().getId();
- var originalTransactionAmount = job.getTransactionAmount();
+ var originalTransactionTypeId = job.transactionType().id();
+ var originalTransactionAmount = job.transactionAmount();
// Find a different job type that has a different amount than the
// job's original type
@@ -895,11 +895,11 @@ void testUpdateJob() throws Exception {
// Create a new job object with a different jobtype and the same id
var now = new Date();
var editedJob = UpdatedTransaction.with()
- .id(job.getId())
- .accountId(account.getAccountId())
- .transactionTypeId(newJobType.getId())
+ .id(job.id())
+ .accountId(account.accountId())
+ .transactionTypeId(newJobType.id())
.transactionTime(now)
- .transactionAmount(newJobType.getTransactionAmount())
+ .transactionAmount(newJobType.transactionAmount())
.build();
// Build the HTTP request
@@ -928,18 +928,18 @@ void testUpdateJob() throws Exception {
assertEquals(200, response.getStatus());
assertEquals("application/json", response.getContentType());
var updatedJobs = mapper.readValue(getBinaryContent(response), new TypeReference>() { });
- var editedJobFromDatabase = updatedJobs.stream().filter(t->t.getId() == job.getId()).collect(Collectors.toList()).get(0);
+ var editedJobFromDatabase = updatedJobs.stream().filter(t->t.id() == job.id()).collect(Collectors.toList()).get(0);
- assertEquals(editedJob.getTransactionTypeId(), editedJobFromDatabase.getTransactionType().getId().intValue());
- assertThat(editedJobFromDatabase.getTransactionTime().getTime()).isGreaterThan(job.getTransactionTime().getTime());
- assertEquals(editedJob.getTransactionAmount(), editedJobFromDatabase.getTransactionAmount(), 0.0);
+ assertEquals(editedJob.transactionTypeId(), editedJobFromDatabase.transactionType().id());
+ assertThat(editedJobFromDatabase.transactionTime().getTime()).isGreaterThan(job.transactionTime().getTime());
+ assertEquals(editedJob.transactionAmount(), editedJobFromDatabase.transactionAmount(), 0.0);
}
@Test
void testGetPayments() throws Exception {
// Set up the request
var account = getJadAccount();
- var request = buildGetUrl(String.format("/payments/%d", account.getAccountId()));
+ var request = buildGetUrl(String.format("/payments/%d", account.accountId()));
// Create a response object that will receive and hold the servlet output
var response = new MockHttpServletResponse();
@@ -1000,15 +1000,15 @@ void testGetPaymenttypes() throws Exception {
void testRegisterPayments() throws Exception {
// Create the request
var account = getJadAccount();
- var originalBalance = account.getBalance();
+ var originalBalance = account.balance();
var paymentTypes = getPaymenttypes();
var payment = PerformedTransaction.with()
.account(account)
- .transactionTypeId(paymentTypes.get(0).getId())
- .transactionAmount(paymentTypes.get(0).getTransactionAmount())
+ .transactionTypeId(paymentTypes.get(0).id())
+ .transactionAmount(paymentTypes.get(0).transactionAmount())
.transactionDate(new Date())
.build();
- account.setBalance(0.0);
+ account = Account.with(account).balance(0.0).build();
var paymentAsJson = ServletTestBase.mapper.writeValueAsString(payment);
var request = buildPostUrl("/registerpayment");
request.setBodyContent(paymentAsJson);
@@ -1035,8 +1035,8 @@ void testRegisterPayments() throws Exception {
assertEquals("application/json", response.getContentType());
var result = ServletTestBase.mapper.readValue(response.getOutputStreamContent(), Account.class);
- assertEquals("jad", result.getUsername());
- assertThat(result.getBalance()).isLessThan(originalBalance);
+ assertEquals("jad", result.username());
+ assertThat(result.balance()).isLessThan(originalBalance);
}
@Test
@@ -1044,7 +1044,7 @@ void testModifyJobtype() throws Exception {
// Find a jobtype to modify
var jobtypes = getJobtypes();
var jobtype = jobtypes.get(0);
- var originalAmount = jobtype.getTransactionAmount();
+ var originalAmount = jobtype.transactionAmount();
// Modify the amount of the jobtype
jobtype = TransactionType.with(jobtype).transactionAmount(originalAmount + 1).build();
@@ -1077,7 +1077,7 @@ void testModifyJobtype() throws Exception {
List updatedJobtypes = mapper.readValue(getBinaryContent(response), new TypeReference>() {});
var updatedJobtype = updatedJobtypes.get(0);
- assertThat(updatedJobtype.getTransactionAmount()).isGreaterThan(originalAmount);
+ assertThat(updatedJobtype.transactionAmount()).isGreaterThan(originalAmount);
}
@Test
@@ -1130,7 +1130,7 @@ void testModifyPaymenttype() throws Exception {
// Find a payment type to modify
var paymenttypes = getPaymenttypes();
var paymenttype = paymenttypes.get(1);
- var originalAmount = paymenttype.getTransactionAmount();
+ var originalAmount = paymenttype.transactionAmount();
// Modify the amount of the payment type
paymenttype = TransactionType.with(paymenttype).transactionAmount(originalAmount + 1).build();
@@ -1163,7 +1163,7 @@ void testModifyPaymenttype() throws Exception {
var updatedPaymenttypes = mapper.readValue(getBinaryContent(response), new TypeReference>() {});
TransactionType updatedPaymenttype = updatedPaymenttypes.get(0);
- assertThat(updatedPaymenttype.getTransactionAmount()).isGreaterThan(originalAmount);
+ assertThat(updatedPaymenttype.transactionAmount()).isGreaterThan(originalAmount);
}
@Test
@@ -1477,8 +1477,8 @@ void testNotifications() throws Exception {
assertEquals(200, notificationsResponse2.getStatus());
assertEquals("application/json", notificationsResponse2.getContentType());
var notificationsToJad2 = mapper.readValue(getBinaryContent(notificationsResponse2), new TypeReference>() {});
- assertEquals(utbetalt.getTitle(), notificationsToJad2.get(0).getTitle());
- assertEquals(utbetalt.getMessage(), notificationsToJad2.get(0).getMessage());
+ assertEquals(utbetalt.title(), notificationsToJad2.get(0).title());
+ assertEquals(utbetalt.message(), notificationsToJad2.get(0).message());
}
@Test
@@ -1696,8 +1696,8 @@ void testPostAdminStatus() throws Exception {
assertEquals(200, response.getStatus());
assertEquals("application/json", response.getContentType());
var updatedStatus = mapper.readValue(getBinaryContent(response), AdminStatus.class);
- assertEquals(user, updatedStatus.getUser());
- assertTrue(updatedStatus.isAdministrator());
+ assertEquals(user, updatedStatus.user());
+ assertTrue(updatedStatus.administrator());
}
@Test
@@ -1741,8 +1741,8 @@ void testPostChangeAdminStatus() throws Exception {
assertEquals(200, response.getStatus());
assertEquals("application/json", response.getContentType());
var updatedStatus = mapper.readValue(getBinaryContent(response), AdminStatus.class);
- assertEquals(user, updatedStatus.getUser());
- assertTrue(updatedStatus.isAdministrator());
+ assertEquals(user, updatedStatus.user());
+ assertTrue(updatedStatus.administrator());
}
@Test
@@ -1926,12 +1926,12 @@ void testDisplayTextsWithUnknownLocale() throws Exception {
assertEquals(500, response.getStatus());
assertEquals("application/json", response.getContentType());
var errorMessage = mapper.readValue(getBinaryContent(response), ErrorMessage.class);
- assertEquals(500, errorMessage.getStatus());
- assertThat(errorMessage.getMessage()).startsWith("Unknown locale");
+ assertEquals(500, errorMessage.status());
+ assertThat(errorMessage.message()).startsWith("Unknown locale");
}
private TransactionType findJobTypeWithDifferentIdAndAmount(Integer transactionTypeId, double amount) {
- return getJobtypes().stream().filter(t->!t.getId().equals(transactionTypeId)).filter(t->t.getTransactionAmount() != amount).collect(Collectors.toList()).get(0);
+ return getJobtypes().stream().filter(t->t.id() != transactionTypeId).filter(t->t.transactionAmount() != amount).collect(Collectors.toList()).get(0);
}
diff --git a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AccountResourceTest.java b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AccountResourceTest.java
index baeb5e63..82bdcac0 100644
--- a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AccountResourceTest.java
+++ b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AccountResourceTest.java
@@ -66,8 +66,8 @@ void testGetAccount() throws Exception {
var result = resource.getAccount("jad");
// Check the result
- assertEquals("jad", result.getUsername());
- assertEquals(673.0, result.getBalance(), 0.0);
+ assertEquals("jad", result.username());
+ assertEquals(673.0, result.balance(), 0.0);
}
/**
@@ -137,8 +137,8 @@ void testGetAccountWhenLoggedInAsAdministrator() throws Exception {
var result = resource.getAccount("jad");
// Check the response
- assertEquals("jad", result.getUsername());
- assertEquals(673.0, result.getBalance(), 0.0);
+ assertEquals("jad", result.username());
+ assertEquals(673.0, result.balance(), 0.0);
}
@Test
diff --git a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminJobsTest.java b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminJobsTest.java
index 33220bbb..a6d10ed3 100644
--- a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminJobsTest.java
+++ b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminJobsTest.java
@@ -49,7 +49,7 @@ void testDeleteAllJobsOfUser() {
// Set up the POST argument for the delete
var account = getJodAccount();
var jobs = getJodJobs();
- var jobIds = Arrays.asList(jobs.get(0).getId(), jobs.get(1).getId());
+ var jobIds = Arrays.asList(jobs.get(0).id(), jobs.get(1).id());
var accountWithJobIds = AccountWithJobIds.with().account(account).jobIds(jobIds).build();
// Do the delete
@@ -69,7 +69,7 @@ void testDeleteSomeJobsOfUser() {
// Set up the POST argument for the delete
var account = getJodAccount();
var jobs = getJodJobs();
- var idsOfJobsToDelete = Arrays.asList(jobs.get(0).getId());
+ var idsOfJobsToDelete = Arrays.asList(jobs.get(0).id());
var accountWithJobIds = AccountWithJobIds.with().account(account).jobIds(idsOfJobsToDelete).build();
// Do the delete
diff --git a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminJobtypeTest.java b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminJobtypeTest.java
index b8aaef30..04b40d41 100644
--- a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminJobtypeTest.java
+++ b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminJobtypeTest.java
@@ -49,7 +49,7 @@ void testModifyJobtype() {
// Find a jobtype to modify
var jobtypes = getJobtypes();
var jobtype = jobtypes.get(0);
- var originalAmount = jobtype.getTransactionAmount();
+ var originalAmount = jobtype.transactionAmount();
// Modify the amount of the jobtype
jobtype = TransactionType.with(jobtype).transactionAmount(originalAmount + 1).build();
@@ -60,7 +60,7 @@ void testModifyJobtype() {
// Verify that the updated amount is larger than the original amount
var updatedJobtype = updatedJobtypes.get(0);
- assertThat(updatedJobtype.getTransactionAmount()).isGreaterThan(originalAmount);
+ assertThat(updatedJobtype.transactionAmount()).isGreaterThan(originalAmount);
}
@Test
diff --git a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminPaymenttypeTest.java b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminPaymenttypeTest.java
index d0a89840..7c005cb1 100644
--- a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminPaymenttypeTest.java
+++ b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminPaymenttypeTest.java
@@ -49,7 +49,7 @@ void testModifyPaymenttype() {
// Find a payment type to modify
var paymenttypes = getPaymenttypes();
var paymenttype = paymenttypes.get(1);
- var originalAmount = paymenttype.getTransactionAmount();
+ var originalAmount = paymenttype.transactionAmount();
// Modify the amount of the payment type
paymenttype = TransactionType.with(paymenttype).transactionAmount(originalAmount + 1).build();
@@ -60,7 +60,7 @@ void testModifyPaymenttype() {
// Verify that the updated amount is larger than the original amount
var updatedPaymenttype = updatedPaymenttypes.get(0);
- assertThat(updatedPaymenttype.getTransactionAmount()).isGreaterThan(originalAmount);
+ assertThat(updatedPaymenttype.transactionAmount()).isGreaterThan(originalAmount);
}
@Test
diff --git a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminUserResourceTest.java b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminUserResourceTest.java
index 10eab177..88ba18d7 100644
--- a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminUserResourceTest.java
+++ b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/AdminUserResourceTest.java
@@ -208,8 +208,8 @@ void testAdminStatusWhenUserIsAdministrator() {
.build();
var status = resource.adminStatus(user);
- assertEquals(user, status.getUser());
- assertTrue(status.isAdministrator());
+ assertEquals(user, status.user());
+ assertTrue(status.administrator());
}
@Test
@@ -233,8 +233,8 @@ void testAdminStatusWhenUserIsNotAdministrator() {
.lastname(newLastname)
.build();
var status = resource.adminStatus(user);
- assertEquals(user, status.getUser());
- assertFalse(status.isAdministrator());
+ assertEquals(user, status.user());
+ assertFalse(status.administrator());
}
@Test
@@ -261,8 +261,8 @@ void testChangeAdminStatusMakeUserAdministrator() {
var status = AdminStatus.with().user(user).administrator(true).build();
var changedStatus = resource.changeAdminStatus(status);
- assertEquals(user, changedStatus.getUser());
- assertTrue(changedStatus.isAdministrator());
+ assertEquals(user, changedStatus.user());
+ assertTrue(changedStatus.administrator());
}
@Test
@@ -289,8 +289,8 @@ void testChangeAdminStatusMakeUserNotAdministrator() {
var status = AdminStatus.with().user(user).administrator(false).build();
var changedStatus = resource.changeAdminStatus(status);
- assertEquals(user, changedStatus.getUser());
- assertFalse(changedStatus.isAdministrator());
+ assertEquals(user, changedStatus.user());
+ assertFalse(changedStatus.administrator());
}
@Test
@@ -317,8 +317,8 @@ void testChangeAdminStatusSetUserAdministratorWhenUserAlreadyAdministrator() {
var status = AdminStatus.with().user(user).administrator(true).build();
var changedStatus = resource.changeAdminStatus(status);
- assertEquals(user, changedStatus.getUser());
- assertTrue(changedStatus.isAdministrator());
+ assertEquals(user, changedStatus.user());
+ assertTrue(changedStatus.administrator());
}
@Test
@@ -343,8 +343,8 @@ void testChangeAdminStatusAdminRoleNotPresent() {
var status = AdminStatus.with().user(user).administrator(true).build();
var changedStatus = resource.changeAdminStatus(status);
- assertEquals(user, changedStatus.getUser());
- assertFalse(changedStatus.isAdministrator());
+ assertEquals(user, changedStatus.user());
+ assertFalse(changedStatus.administrator());
}
@Test
diff --git a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/JobResourceTest.java b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/JobResourceTest.java
index f4dfb3ee..952759a4 100644
--- a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/JobResourceTest.java
+++ b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/JobResourceTest.java
@@ -57,12 +57,12 @@ class JobResourceTest extends ServletTestBase {
void testRegisterJob() throws Exception {
// Create the request
var account = getJadAccount();
- var originalBalance = account.getBalance();
+ var originalBalance = account.balance();
var jobTypes = getJobtypes();
var job = PerformedTransaction.with()
.account(account)
- .transactionTypeId(jobTypes.get(0).getId())
- .transactionAmount(jobTypes.get(0).getTransactionAmount())
+ .transactionTypeId(jobTypes.get(0).id())
+ .transactionAmount(jobTypes.get(0).transactionAmount())
.transactionDate(new Date())
.build();
@@ -84,8 +84,7 @@ void testRegisterJob() throws Exception {
// Inject fake OSGi service UkelonnService
var ukelonn = mock(UkelonnService.class);
- var accountWithUpdatedBalance = copyAccount(account);
- accountWithUpdatedBalance.setBalance(account.getBalance() + job.getTransactionAmount());
+ var accountWithUpdatedBalance = Account.with(account).balance(account.balance() + job.transactionAmount()).build();
when(ukelonn.registerPerformedJob(any())).thenReturn(accountWithUpdatedBalance);
resource.ukelonn = ukelonn;
@@ -93,8 +92,8 @@ void testRegisterJob() throws Exception {
var result = resource.doRegisterJob(job);
// Check the response
- assertEquals("jad", result.getUsername());
- assertThat(result.getBalance()).isGreaterThan(originalBalance);
+ assertEquals("jad", result.username());
+ assertThat(result.balance()).isGreaterThan(originalBalance);
}
/**
@@ -110,8 +109,8 @@ void testRegisterJobOtherUsername() throws Exception {
var jobTypes = getJobtypes();
var job = PerformedTransaction.with()
.account(account)
- .transactionTypeId(jobTypes.get(0).getId())
- .transactionAmount(jobTypes.get(0).getTransactionAmount())
+ .transactionTypeId(jobTypes.get(0).id())
+ .transactionAmount(jobTypes.get(0).transactionAmount())
.transactionDate(new Date())
.build();
@@ -149,12 +148,12 @@ void testRegisterJobOtherUsername() throws Exception {
void testRegisterJobtWhenLoggedInAsAdministrator() throws Exception {
// Create the request
var account = getJadAccount();
- var originalBalance = account.getBalance();
+ var originalBalance = account.balance();
var jobTypes = getJobtypes();
var job = PerformedTransaction.with()
.account(account)
- .transactionTypeId(jobTypes.get(0).getId())
- .transactionAmount(jobTypes.get(0).getTransactionAmount())
+ .transactionTypeId(jobTypes.get(0).id())
+ .transactionAmount(jobTypes.get(0).transactionAmount())
.transactionDate(new Date())
.build();
@@ -176,8 +175,7 @@ void testRegisterJobtWhenLoggedInAsAdministrator() throws Exception {
// Inject fake OSGi service UkelonnService
var ukelonn = mock(UkelonnService.class);
- var accountWithUpdatedBalance = copyAccount(account);
- accountWithUpdatedBalance.setBalance(account.getBalance() + job.getTransactionAmount());
+ var accountWithUpdatedBalance = Account.with(account).balance(account.balance() + job.transactionAmount()).build();
when(ukelonn.registerPerformedJob(any())).thenReturn(accountWithUpdatedBalance);
resource.ukelonn = ukelonn;
@@ -185,8 +183,8 @@ void testRegisterJobtWhenLoggedInAsAdministrator() throws Exception {
var result = resource.doRegisterJob(job);
// Check the response
- assertEquals("jad", result.getUsername());
- assertThat(result.getBalance()).isGreaterThan(originalBalance);
+ assertEquals("jad", result.username());
+ assertThat(result.balance()).isGreaterThan(originalBalance);
}
@Test
@@ -196,8 +194,8 @@ void testRegisterJobNoUsername() throws Exception {
var jobTypes = getJobtypes();
var job = PerformedTransaction.with()
.account(account)
- .transactionTypeId(jobTypes.get(0).getId())
- .transactionAmount(jobTypes.get(0).getTransactionAmount())
+ .transactionTypeId(jobTypes.get(0).id())
+ .transactionAmount(jobTypes.get(0).transactionAmount())
.transactionDate(new Date())
.build();
@@ -240,8 +238,8 @@ void testRegisterJobInternalServerError() throws Exception {
var jobTypes = getJobtypes();
var job = PerformedTransaction.with()
.account(account)
- .transactionTypeId(jobTypes.get(0).getId())
- .transactionAmount(jobTypes.get(0).getTransactionAmount())
+ .transactionTypeId(jobTypes.get(0).id())
+ .transactionAmount(jobTypes.get(0).transactionAmount())
.transactionDate(new Date())
.build();
@@ -276,12 +274,12 @@ void testUpdateJob() {
var account = getJadAccount();
var job = getJadJobs().get(0);
- var jobId = job.getId();
+ var jobId = job.id();
// Save initial values of the job for comparison later
- var originalTransactionTypeId = job.getTransactionType().getId();
- var originalTransactionTime = job.getTransactionTime();
- var originalTransactionAmount = job.getTransactionAmount();
+ var originalTransactionTypeId = job.transactionType().id();
+ var originalTransactionTime = job.transactionTime();
+ var originalTransactionAmount = job.transactionAmount();
// Find a different job type that has a different amount
var newJobType = findJobTypeWithDifferentIdAndAmount(ukelonn, originalTransactionTypeId, originalTransactionAmount);
@@ -290,20 +288,20 @@ void testUpdateJob() {
var now = new Date();
var editedJob = UpdatedTransaction.with()
.id(jobId)
- .accountId(account.getAccountId())
- .transactionTypeId(newJobType.getId())
+ .accountId(account.accountId())
+ .transactionTypeId(newJobType.id())
.transactionTime(now)
- .transactionAmount(newJobType.getTransactionAmount())
+ .transactionAmount(newJobType.transactionAmount())
.build();
when(ukelonn.updateJob(any())).thenReturn(Arrays.asList(convertUpdatedTransaction(editedJob)));
var updatedJobs = resource.doUpdateJob(editedJob);
- var editedJobFromDatabase = updatedJobs.stream().filter(t->t.getId() == job.getId()).collect(Collectors.toList()).get(0);
+ var editedJobFromDatabase = updatedJobs.stream().filter(t->t.id() == job.id()).collect(Collectors.toList()).get(0);
- assertEquals(editedJob.getTransactionTypeId(), editedJobFromDatabase.getTransactionType().getId().intValue());
- assertThat(editedJobFromDatabase.getTransactionTime().getTime()).isGreaterThan(originalTransactionTime.getTime());
- assertEquals(editedJob.getTransactionAmount(), editedJobFromDatabase.getTransactionAmount(), 0.0);
+ assertEquals(editedJob.transactionTypeId(), editedJobFromDatabase.transactionType().id());
+ assertThat(editedJobFromDatabase.transactionTime().getTime()).isGreaterThan(originalTransactionTime.getTime());
+ assertEquals(editedJob.transactionAmount(), editedJobFromDatabase.transactionAmount(), 0.0);
}
@Test
@@ -329,7 +327,7 @@ void testUpdateJobGetSQLException() throws Exception {
}
private TransactionType findJobTypeWithDifferentIdAndAmount(UkelonnService ukelonn, Integer transactionTypeId, double amount) {
- return getJobtypes().stream().filter(t->!t.getId().equals(transactionTypeId)).filter(t->t.getTransactionAmount() != amount).collect(Collectors.toList()).get(0);
+ return getJobtypes().stream().filter(t->!(t.id() == transactionTypeId)).filter(t->t.transactionAmount() != amount).collect(Collectors.toList()).get(0);
}
}
diff --git a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/JobsTest.java b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/JobsTest.java
index e08d855d..6966a1b3 100644
--- a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/JobsTest.java
+++ b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/JobsTest.java
@@ -32,7 +32,7 @@ void testGetJobs() {
var ukelonn = mock(UkelonnService.class);
when(ukelonn.getJobs(anyInt())).thenReturn(getJadJobs());
resource.ukelonn = ukelonn;
- var jobs = resource.jobs(account.getAccountId());
+ var jobs = resource.jobs(account.accountId());
assertEquals(10, jobs.size());
}
diff --git a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/LoginTest.java b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/LoginTest.java
index 9d4ad48d..9d26e00d 100644
--- a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/LoginTest.java
+++ b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/LoginTest.java
@@ -67,8 +67,8 @@ void testLoginOk() throws Exception {
var result = resource.doLogin(credentials);
// Check the response
- assertThat(result.getRoles()).isNotEmpty();
- assertEquals("", result.getErrorMessage());
+ assertThat(result.roles()).isNotEmpty();
+ assertEquals("", result.errorMessage());
}
@Test
@@ -92,8 +92,8 @@ void testAdminLoginOk() throws Exception {
var result = resource.doLogin(credentials);
// Check the response
- assertThat(result.getRoles()).isNotEmpty();
- assertEquals("", result.getErrorMessage());
+ assertThat(result.roles()).isNotEmpty();
+ assertEquals("", result.errorMessage());
}
@Test
@@ -117,8 +117,8 @@ void testLoginUnknownUser() throws Exception {
LoginResult result = resource.doLogin(credentials);
// Check the response
- assertEquals(0, result.getRoles().length);
- assertEquals("Unknown account", result.getErrorMessage());
+ assertEquals(0, result.roles().length);
+ assertEquals("Unknown account", result.errorMessage());
}
@Test
@@ -142,8 +142,8 @@ void testLoginWrongPassword() throws Exception {
LoginResult result = resource.doLogin(credentials);
// Check the response
- assertEquals(0, result.getRoles().length);
- assertEquals("Wrong password", result.getErrorMessage());
+ assertEquals(0, result.roles().length);
+ assertEquals("Wrong password", result.errorMessage());
}
@Test
@@ -166,8 +166,8 @@ void testLoginLockedAccount() throws Exception {
createSubjectAndBindItToThread(request, response);
LoginResult result = resource.doLogin(credentials);
// Check the response
- assertEquals(0, result.getRoles().length);
- assertEquals("Locked account", result.getErrorMessage());
+ assertEquals(0, result.roles().length);
+ assertEquals("Locked account", result.errorMessage());
} finally {
unlockAccount("jad");
}
@@ -187,8 +187,8 @@ void testLoginWithAuthenticationException() {
resource.setLogservice(logservice);
LoginResult result = resource.doLogin(credentials);
// Check the response
- assertEquals(0, result.getRoles().length);
- assertEquals("Unknown error", result.getErrorMessage());
+ assertEquals(0, result.roles().length);
+ assertEquals("Unknown error", result.errorMessage());
}
@Test
@@ -238,8 +238,8 @@ void testGetLoginStateWhenLoggedIn() throws Exception {
LoginResult result = resource.loginStatus();
// Check the response
- assertThat(result.getRoles()).isNotEmpty();
- assertEquals("", result.getErrorMessage());
+ assertThat(result.roles()).isNotEmpty();
+ assertEquals("", result.errorMessage());
}
/**
@@ -271,8 +271,8 @@ void testGetLoginStateWhenNotLoggedIn() throws Exception {
LoginResult result = resource.loginStatus();
// Check the response
- assertEquals(0, result.getRoles().length);
- assertEquals("", result.getErrorMessage());
+ assertEquals(0, result.roles().length);
+ assertEquals("", result.errorMessage());
}
private void lockAccount(String username) {
diff --git a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/LogoutTest.java b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/LogoutTest.java
index f6636a44..8172c33a 100644
--- a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/LogoutTest.java
+++ b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/LogoutTest.java
@@ -53,8 +53,8 @@ void testLogoutOk() throws Exception {
var result = resource.doLogout();
// Check the response
- assertEquals(0, result.getRoles().length);
- assertEquals("", result.getErrorMessage());
+ assertEquals(0, result.roles().length);
+ assertEquals("", result.errorMessage());
}
/**
@@ -80,7 +80,7 @@ void testLogoutNotLoggedIn() throws Exception {
var result = resource.doLogout();
// Check the response
- assertEquals(0, result.getRoles().length);
- assertEquals("", result.getErrorMessage());
+ assertEquals(0, result.roles().length);
+ assertEquals("", result.errorMessage());
}
}
diff --git a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/PaymentsTest.java b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/PaymentsTest.java
index 589b9684..ddc7d46c 100644
--- a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/PaymentsTest.java
+++ b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/PaymentsTest.java
@@ -32,7 +32,7 @@ void testGetPayments() {
var ukelonn = mock(UkelonnService.class);
when(ukelonn.getPayments(anyInt())).thenReturn(getJadPayments());
resource.ukelonn = ukelonn;
- var jobs = resource.payments(account.getAccountId());
+ var jobs = resource.payments(account.accountId());
assertEquals(10, jobs.size());
}
diff --git a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/RegisterPaymentTest.java b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/RegisterPaymentTest.java
index 9dc45dc7..d6a5dce6 100644
--- a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/RegisterPaymentTest.java
+++ b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/RegisterPaymentTest.java
@@ -24,6 +24,7 @@
import org.junit.jupiter.api.Test;
import no.priv.bang.ukelonn.UkelonnService;
+import no.priv.bang.ukelonn.beans.Account;
import no.priv.bang.ukelonn.beans.PerformedTransaction;
class RegisterPaymentTest {
@@ -32,13 +33,13 @@ class RegisterPaymentTest {
void testRegisterPayment() throws Exception {
// Create the request
var account = getJadAccount();
- var originalBalance = account.getBalance();
- account.setBalance(0.0);
+ var originalBalance = account.balance();
+ account = Account.with(account).balance(0.0).build();
var paymenttypes = getPaymenttypes();
var payment = PerformedTransaction.with()
.account(account)
- .transactionTypeId(paymenttypes.get(0).getId())
- .transactionAmount(account.getBalance())
+ .transactionTypeId(paymenttypes.get(0).id())
+ .transactionAmount(account.balance())
.transactionDate(new Date())
.build();
@@ -54,7 +55,7 @@ void testRegisterPayment() throws Exception {
var result = resource.doRegisterPayment(payment);
// Check the response
- assertEquals("jad", result.getUsername());
- assertThat(result.getBalance()).isLessThan(originalBalance);
+ assertEquals("jad", result.username());
+ assertThat(result.balance()).isLessThan(originalBalance);
}
}
diff --git a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/StatisticsTest.java b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/StatisticsTest.java
index 423ee3a3..dd23b91a 100644
--- a/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/StatisticsTest.java
+++ b/ukelonn.web.services/src/test/java/no/priv/bang/ukelonn/api/resources/StatisticsTest.java
@@ -38,7 +38,7 @@ void testEarningsSumOverYear() {
var username = "jad";
var earningsSumOverYear = resource.earningsSumOverYear(username);
assertThat(earningsSumOverYear).isNotEmpty();
- assertEquals(2016, earningsSumOverYear.get(0).getYear());
+ assertEquals(2016, earningsSumOverYear.get(0).year());
}
@Test
@@ -51,7 +51,7 @@ void testEarningsSumOverMonth() {
var username = "jad";
var earningsSumOverYear = resource.earningsSumOverMonth(username);
assertThat(earningsSumOverYear).isNotEmpty();
- assertEquals(2016, earningsSumOverYear.get(0).getYear());
+ assertEquals(2016, earningsSumOverYear.get(0).year());
}
}