Skip to content
This repository has been archived by the owner on Dec 3, 2019. It is now read-only.

Волгин Т.А. #17

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/main/java/com/moneytransfer/dao/AccountDAO.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
import com.moneytransfer.model.UserTransaction;

import java.math.BigDecimal;
import java.util.List;
import java.util.Set;

public interface AccountDAO {

Set<Account> getAllAccounts() throws CustomException;
List<Account> getAllAccounts() throws CustomException;

Account getAccountById(long accountId) throws CustomException;

Expand Down
9 changes: 7 additions & 2 deletions src/main/java/com/moneytransfer/dao/H2DAOFactory.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.moneytransfer.dao;

import com.moneytransfer.dao.impl.AccountDAOImpl;
import com.moneytransfer.dao.impl.AccountDAOImplHashMap;
import com.moneytransfer.dao.impl.UserDAOImpl;
import com.moneytransfer.dao.impl.UserDAOImplHashMap;
import com.moneytransfer.exception.CustomException;
import com.moneytransfer.utils.Utils;

Expand All @@ -25,8 +27,11 @@ public class H2DAOFactory extends DAOFactory {
private static final String h2_password = Utils.getStringProperty("h2_password");
private static Logger log = Logger.getLogger(H2DAOFactory.class);

private static final UserDAOImpl userDAO = new UserDAOImpl();
private static final AccountDAOImpl accountDAO = new AccountDAOImpl();
// private static final UserDAOImpl userDAO = new UserDAOImpl();
// private static final AccountDAOImpl accountDAO = new AccountDAOImpl();

private static final UserDAOImplHashMap userDAO = new UserDAOImplHashMap();
private static final AccountDAOImplHashMap accountDAO = new AccountDAOImplHashMap();

static {
// init: load driver
Expand Down
12 changes: 5 additions & 7 deletions src/main/java/com/moneytransfer/dao/impl/AccountDAOImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class AccountDAOImpl implements AccountDAO {
Expand All @@ -32,11 +34,11 @@ public class AccountDAOImpl implements AccountDAO {
/**
* Get all accounts.
*/
public Set<Account> getAllAccounts() throws CustomException {
public List<Account> getAllAccounts() throws CustomException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Set<Account> allAccounts = new HashSet<>();
List<Account> allAccounts = new ArrayList<>();
try {
conn = H2DAOFactory.getConnection();
stmt = conn.prepareStatement(SQL_GET_ALL_ACC);
Expand Down Expand Up @@ -103,11 +105,7 @@ public Account getAccountByUser(String user, String currency) throws CustomExcep
log.debug("Retrieve Account By userId: " + acc);
}
}
return getAllAccounts()
.stream()
.filter(account -> account.getUserName().equals(user) && account.getCurrencyCode().equals(currency))
.findFirst()
.orElse(null);
return acc;
} catch (SQLException e) {
throw new CustomException("getAccountById(): Error reading account data", e);
} finally {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package com.moneytransfer.dao.impl;

import com.moneytransfer.dao.AccountDAO;
import com.moneytransfer.exception.CustomException;
import com.moneytransfer.model.Account;
import com.moneytransfer.model.UserTransaction;

import java.math.BigDecimal;
import java.util.*;

public class AccountDAOImplHashMap implements AccountDAO {

HashMap<Long, Account> accounts = new HashMap<>();
long counter = 1;

@Override
public List<Account> getAllAccounts() throws CustomException {
List<Account> result = new ArrayList<>();

for (Account value : accounts.values()) {
result.add(value);
}
return result;
}

@Override
public Account getAccountById(long accountId) throws CustomException {
return accounts.get(accountId);
}

@Override
public Account getAccountByUser(String user, String currency) throws CustomException {
return getAllAccounts()
.stream()
.filter(account -> account.getUserName().equals(user) && account.getCurrencyCode().equals(currency))
.findFirst()
.orElse(null);
}

@Override
public long createAccount(Account account) throws CustomException {
accounts.put(counter, account);
return counter++;
}

@Override
public int deleteAccountById(long accountId) throws CustomException {
if (accounts.containsKey(accountId)) {
accounts.remove(accountId);
return 1;
}
return 0;
}

@Override
public int updateAccountBalance(long accountId, BigDecimal deltaAmount) throws CustomException {
if (accounts.containsKey(accountId)) {
accounts.get(accountId).getBalance().add(deltaAmount);
return 1;
}
return 0;
}

@Override
public int transferAccountBalance(UserTransaction userTransaction) throws CustomException {
long from = userTransaction.getFromAccountId();
long to = userTransaction.getToAccountId();
if (accounts.containsKey(from) && accounts.containsKey(to)) {
updateAccountBalance(from, userTransaction.getAmount().negate());
updateAccountBalance(to, userTransaction.getAmount());
return 2;
}
return 0;
}
}
22 changes: 12 additions & 10 deletions src/main/java/com/moneytransfer/dao/impl/UserDAOImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,10 @@ public class UserDAOImpl implements UserDAO {
private final static String SQL_GET_USER_BY_ID = "SELECT * FROM User WHERE UserId = ? ";
private final static String SQL_GET_ALL_USERS = "SELECT * FROM User";
private final static String SQL_GET_USER_BY_NAME = "SELECT * FROM User WHERE UserName = ? ";
private final static String SQL_INSERT_USER = "INSERT INTO User (UserId, UserName, EmailAddress) VALUES (?, ?, ?)";
private final static String SQL_INSERT_USER = "INSERT INTO User (UserName, EmailAddress) VALUES (?, ?)";
private final static String SQL_UPDATE_USER = "UPDATE User SET UserName = ?, EmailAddress = ? WHERE UserId = ? ";
private final static String SQL_DELETE_USER_BY_ID = "DELETE FROM User WHERE UserId = ? ";

private List<User> fetched = new ArrayList<>();

/**
* Find all users
*/
Expand All @@ -42,7 +40,6 @@ public List<User> getAllUsers() throws CustomException {
if (log.isDebugEnabled())
log.debug("getAllUsers() Retrieve User: " + u);
}
fetched.addAll(users);
return users;
} catch (SQLException e) {
throw new CustomException("Error reading user data", e);
Expand Down Expand Up @@ -109,24 +106,29 @@ public User getUserByName(String userName) throws CustomException {
public long insertUser(User user) throws CustomException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet generatedKeys = null;
try {
conn = H2DAOFactory.getConnection();
stmt = conn.prepareStatement(SQL_INSERT_USER, Statement.RETURN_GENERATED_KEYS);
long id = getAllUsers().stream().mapToLong(User::getUserId).max().orElse(0) + 1;
stmt.setLong(1, id);
stmt.setString(2, user.getUserName());
stmt.setString(3, user.getEmailAddress());
stmt.setString(1, user.getUserName());
stmt.setString(2, user.getEmailAddress());
int affectedRows = stmt.executeUpdate();
if (affectedRows == 0) {
log.error("insertUser(): Creating user failed, no rows affected." + user);
throw new CustomException("Users Cannot be created");
}
return id;
generatedKeys = stmt.getGeneratedKeys();
if (generatedKeys.next()) {
return generatedKeys.getLong(1);
} else {
log.error("Error Inserting User :" + user);
throw new CustomException("Error creating user data");
}
} catch (SQLException e) {
log.error("Error Inserting User :" + user);
throw new CustomException("Error creating user data", e);
} finally {
DbUtils.closeQuietly(conn);
DbUtils.closeQuietly(conn, stmt, generatedKeys);
}

}
Expand Down
58 changes: 58 additions & 0 deletions src/main/java/com/moneytransfer/dao/impl/UserDAOImplHashMap.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.moneytransfer.dao.impl;

import com.moneytransfer.dao.UserDAO;
import com.moneytransfer.exception.CustomException;
import com.moneytransfer.model.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class UserDAOImplHashMap implements UserDAO {

HashMap<Long, User> users = new HashMap<>();
long counter = 1;

@Override
public List<User> getAllUsers() throws CustomException {
return new ArrayList<User>(users.values());
}

@Override
public User getUserById(long userId) throws CustomException {
return users.get(userId);
}

@Override
public User getUserByName(String userName) throws CustomException {
return getAllUsers()
.stream()
.filter(account -> account.getUserName().equals(userName))
.findFirst()
.orElse(null);
}

@Override
public long insertUser(User user) throws CustomException {
users.put(counter, user);
return counter++;
}

@Override
public int updateUser(Long userId, User user) throws CustomException {
if (users.containsKey(userId)) {
users.put(userId, user);
return 1;
}
return 0;
}

@Override
public int deleteUser(long userId) throws CustomException {
if (users.containsKey(userId)) {
users.remove(userId);
return 1;
}
return 0;
}
}
25 changes: 18 additions & 7 deletions src/main/java/com/moneytransfer/model/Account.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,27 @@ public boolean equals(Object o) {

@Override
public int hashCode() {
return 1;
int result = (int) (accountId ^ (accountId >>> 32));
result = 31 * result + userName.hashCode();
result = 31 * result + balance.hashCode();
result = 31 * result + currencyCode.hashCode();
return result;
}

@Override
public String toString() {
return "{" +
"\"accountId\":" + accountId +
", \"userName\":\"" + userName + '\"' +
", \"balance\":" + balance +
", \"currencyCode\":\"" + currencyCode + '\"' +
'}';
StringBuilder stringBuilder = new StringBuilder("{");
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут можно было еще тогда уж стринг билдеру задать первоначальный размер буфера )

stringBuilder.append("\"accountId\":")
.append(accountId)
.append(", \"userName\":\"")
.append(userName)
.append('\"')
.append(", \"balance\":")
.append(balance)
.append(", \"currencyCode\":\"")
.append(currencyCode)
.append('\"')
.append('}');
return stringBuilder.toString();
}
}
16 changes: 11 additions & 5 deletions src/main/java/com/moneytransfer/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,16 @@ public int hashCode() {

@Override
public String toString() {
return "{" +
"\"userId\":" + userId +
", \"userName\":\"" + userName + '\"' +
", \"emailAddress\":\"" + emailAddress + '\"' +
'}';
StringBuilder stringBuilder = new StringBuilder("{");
stringBuilder.append("\"userId\":")
.append(userId)
.append(", \"userName\":\"")
.append(userName)
.append('\"')
.append(", \"emailAddress\":\"")
.append(emailAddress)
.append('\"')
.append('}');
return stringBuilder.toString();
}
}
14 changes: 12 additions & 2 deletions src/main/java/com/moneytransfer/model/UserTransaction.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,17 @@ public int hashCode() {

@Override
public String toString() {
return "{" + "\"currencyCode\":\"" + currencyCode + '\"' + ", \"amount\":" + amount + ", \"fromAccountId\":"
+ fromAccountId + ", \"toAccountId\":" + toAccountId + '}';
StringBuilder stringBuilder = new StringBuilder("{");
stringBuilder.append("\"currencyCode\":\"")
.append(currencyCode)
.append('\"')
.append(", \"amount\":")
.append(amount)
.append(", \"fromAccountId\":")
.append(fromAccountId)
.append(", \"toAccountId\":")
.append(toAccountId)
.append('}');
return stringBuilder.toString();
}
}
3 changes: 2 additions & 1 deletion src/main/java/com/moneytransfer/service/AccountService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.moneytransfer.model.Account;
import com.moneytransfer.model.MoneyUtil;

import java.util.List;
import java.util.stream.Collectors;
import org.apache.log4j.Logger;

Expand Down Expand Up @@ -36,7 +37,7 @@ public class AccountService {
@GET
@Path("/all")
public Response getAllAccounts() throws CustomException {
Set<Account> account = daoFactory.getAccountDAO().getAllAccounts();
List<Account> account = daoFactory.getAccountDAO().getAllAccounts();
return Response.ok("[" + account.stream().map(Account::toString).collect(Collectors.joining(",")) + "]").build();
}

Expand Down
3 changes: 0 additions & 3 deletions src/main/java/com/moneytransfer/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ public class UserService {

private static Logger log = Logger.getLogger(UserService.class);

private List<User> allUsers = new ArrayList<>();

/**
* Find by userName
*
Expand Down Expand Up @@ -62,7 +60,6 @@ public User getUserByName(@PathParam("userName") String userName) throws CustomE
@Path("/all")
public Response getAllUsers() throws CustomException {
List<User> users = daoFactory.getUserDAO().getAllUsers();
allUsers.addAll(users);
return Response.ok("[" + users.stream().map(User::toString).collect(Collectors.joining(",")) + "]").build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public void tearDown() {

@Test
public void testGetAllAccounts() throws CustomException {
Set<Account> allAccounts = h2DaoFactory.getAccountDAO().getAllAccounts();
List<Account> allAccounts = h2DaoFactory.getAccountDAO().getAllAccounts();
assertTrue(allAccounts.size() > 1);
}

Expand Down
2 changes: 1 addition & 1 deletion src/test/resources/demo.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

DROP TABLE IF EXISTS User;

CREATE TABLE User (UserId LONG PRIMARY KEY NOT NULL,
CREATE TABLE User (UserId LONG PRIMARY KEY AUTO_INCREMENT NOT NULL,
UserName VARCHAR(30) NOT NULL,
EmailAddress VARCHAR(30) NOT NULL);

Expand Down