Skip to content
This repository has been archived by the owner on Jan 17, 2022. It is now read-only.

Abdusame Ochil-zoda solution #63

Open
wants to merge 6 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
11 changes: 11 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,17 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<!--<version>5.3.4</version>-->
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<!--<version>3.6.28</version>-->
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
16 changes: 16 additions & 0 deletions src/main/java/com/devexperts/account/AccountKey.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.devexperts.account;

import java.util.Objects;

/**
* Unique Account identifier
*
Expand All @@ -17,4 +19,18 @@ private AccountKey(long accountId) {
public static AccountKey valueOf(long accountId) {
return new AccountKey(accountId);
}

// переопределил equals и hashcode
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AccountKey that = (AccountKey) o;
return accountId == that.accountId;
}

@Override
public int hashCode() {
return Objects.hash(accountId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.devexperts.exceptions;

public class AccountNotFoundException extends Exception {
public AccountNotFoundException(String message, Throwable cause) {
super(message, cause);
}

public AccountNotFoundException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.devexperts.exceptions;

public class AmountIsInvalidException extends Exception {
public AmountIsInvalidException(String message, Throwable cause) {
super(message, cause);
}

public AmountIsInvalidException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.devexperts.exceptions;

public class InsufficientAccountBalanceException extends Exception {
public InsufficientAccountBalanceException(String message, Throwable cause) {
super(message, cause);
}

public InsufficientAccountBalanceException(String message) {
super(message);
}
}
27 changes: 25 additions & 2 deletions src/main/java/com/devexperts/rest/AccountController.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,37 @@
package com.devexperts.rest;

import com.devexperts.account.Account;
import com.devexperts.exceptions.AccountNotFoundException;
import com.devexperts.exceptions.AmountIsInvalidException;
import com.devexperts.exceptions.InsufficientAccountBalanceException;
import com.devexperts.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class AccountController extends AbstractAccountController {

public ResponseEntity<Void> transfer(long sourceId, long targetId, double amount) {
return null;
@Autowired
private AccountService accountService;

@PostMapping("operations/transfer")
public ResponseEntity<Void> transfer(@RequestParam long sourceId,
@RequestParam long targetId,
@RequestParam double amount) {
try {
accountService.transferWithChecks(sourceId, targetId, amount);
} catch (AmountIsInvalidException e) {
return ResponseEntity.badRequest().build();
} catch (AccountNotFoundException e) {
return ResponseEntity.notFound().build();
} catch (InsufficientAccountBalanceException e) {
return ResponseEntity.status(500).build();
}
return ResponseEntity.ok().build();
}
}
8 changes: 7 additions & 1 deletion src/main/java/com/devexperts/service/AccountService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.devexperts.service;

import com.devexperts.account.Account;
import com.devexperts.exceptions.AccountNotFoundException;
import com.devexperts.exceptions.AmountIsInvalidException;
import com.devexperts.exceptions.InsufficientAccountBalanceException;

public interface AccountService {

Expand Down Expand Up @@ -33,5 +36,8 @@ public interface AccountService {
* @param target account to transfer money to
* @param amount dollar amount to transfer
* */
void transfer(Account source, Account target, double amount);
//void transfer(Account source, Account target, double amount);

void transferWithChecks(long sourceId, long targetId, double amount)
throws AccountNotFoundException, InsufficientAccountBalanceException, AmountIsInvalidException;
}
68 changes: 58 additions & 10 deletions src/main/java/com/devexperts/service/AccountServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,21 @@

import com.devexperts.account.Account;
import com.devexperts.account.AccountKey;
import com.devexperts.exceptions.AccountNotFoundException;
import com.devexperts.exceptions.AmountIsInvalidException;
import com.devexperts.exceptions.InsufficientAccountBalanceException;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

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

@Service
public class AccountServiceImpl implements AccountService {

private final List<Account> accounts = new ArrayList<>();
private final Map<AccountKey, Account> accounts = new HashMap<>();

@Override
public void clear() {
Expand All @@ -19,19 +25,61 @@ public void clear() {

@Override
public void createAccount(Account account) {
accounts.add(account);
if (!accounts.containsKey(account.getAccountKey())) {
accounts.put(account.getAccountKey(), account);
}
}

@Override
public Account getAccount(long id) {
return accounts.stream()
.filter(account -> account.getAccountKey() == AccountKey.valueOf(id))
.findAny()
.orElse(null);
synchronized (this) {
return accounts.get(AccountKey.valueOf(id));
}
}

private void transfer(Account source, Account target, double amount) {
source.setBalance(source.getBalance() - amount);
target.setBalance(target.getBalance() + amount);
}

@Override
public void transfer(Account source, Account target, double amount) {
//do nothing for now
@Transactional
public void transferWithChecks(long sourceId, long targetId, double amount)
throws AccountNotFoundException, InsufficientAccountBalanceException,
AmountIsInvalidException {

if (amount <= 0) {
throw new AmountIsInvalidException("Amount is invalid");
}

Account sourceAccount = getAccount(sourceId);
Account targetAccount = getAccount(targetId);

if (sourceAccount == null) {
throw new AccountNotFoundException("Source account is not found.");
}

if (targetAccount == null) {
throw new AccountNotFoundException("Target account is not found.");
}
if (sourceId < targetId) {
synchronized (sourceAccount) {
synchronized (targetAccount) {
if (sourceAccount.getBalance() < amount) {
throw new InsufficientAccountBalanceException("Insufficient account balance");
}
transfer(sourceAccount, targetAccount, amount);
}
}
} else {
synchronized (targetAccount) {
synchronized (sourceAccount) {
if (sourceAccount.getBalance() < amount) {
throw new InsufficientAccountBalanceException("Insufficient account balance");
}
transfer(sourceAccount, targetAccount, amount);
}
}
}
}
}
7 changes: 7 additions & 0 deletions src/main/resources/sql.data/accounts.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
create table accounts (
id int8 not null,
first_name varchar(250) not null,
last_name varchar(250),
balance money,
constraint accounts_pkey primary key (id)
);
5 changes: 5 additions & 0 deletions src/main/resources/sql.data/select.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
select a.id, a.first_name, sum(t.amount) total
from accounts a join transfers t on a.id = t.source_id
where t.transfer_time >= '2019-01-01'
group by a.id
having sum(t.amount) > 1000
8 changes: 8 additions & 0 deletions src/main/resources/sql.data/transfers.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
create table transfers (
id int8 not null,
source_id int8 not null,
target_id int8 not null,
amount money not null,
transfer_time timestamp not null,
constraint transfers_pkey primary key (id)
);
126 changes: 126 additions & 0 deletions src/test/java/com/devexperts/rest/AccountControllerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package com.devexperts.rest;

import com.devexperts.account.Account;
import com.devexperts.account.AccountKey;
import com.devexperts.exceptions.AccountNotFoundException;
import com.devexperts.exceptions.AmountIsInvalidException;
import com.devexperts.exceptions.InsufficientAccountBalanceException;
import com.devexperts.service.AccountService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

import static org.junit.jupiter.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;

@ExtendWith(MockitoExtension.class)
class AccountControllerTest {

private MockMvc mvc;

@InjectMocks
private AccountController accountController;

@Mock
private AccountService accountService;

@BeforeEach
public void setup() {
mvc = MockMvcBuilders.standaloneSetup(accountController)
.build();
}

/**
* successful transfer
* */
@Test
void transfer_0K() throws Exception {
MockHttpServletResponse response = mvc.perform(
post("/api/operations/transfer")
.param("sourceId", String.valueOf(1l))
.param("targetId", String.valueOf(2l))
.param("amount", String.valueOf(20.1)))
.andReturn().getResponse();

assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
}

/**
* account is not found
* */
@Test
void transfer_NOT_FOUND() throws Exception {
doThrow(AccountNotFoundException.class).when(accountService)
.transferWithChecks(1L, 2L, 20.1);
MockHttpServletResponse response = mvc.perform(
post("/api/operations/transfer")
.param("sourceId", String.valueOf(1l))
.param("targetId", String.valueOf(2l))
.param("amount", String.valueOf(20.1)))
.andReturn().getResponse();

assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
}

/**
* amount is invalid
* */
@Test
void transfer_BAD_REQUEST() throws Exception {
doThrow(AmountIsInvalidException.class).when(accountService)
.transferWithChecks(1L, 2L, -1.0);
MockHttpServletResponse response = mvc.perform(
post("/api/operations/transfer")
.param("sourceId", String.valueOf(1l))
.param("targetId", String.valueOf(2l))
.param("amount", String.valueOf(-1.0)))
.andReturn().getResponse();

assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
}

/**
* one of the parameters in not present
* */
@Test
void transfer_BAD_REQUEST2() throws Exception {
MockHttpServletResponse response = mvc.perform(
post("/api/operations/transfer")
.param("sourceId", String.valueOf(1l))
.param("amount", String.valueOf(1.0)))
.andReturn().getResponse();

assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
}

/**
* insufficient account balance
* */
@Test
void transfer_INTERNAL_SERVER_ERROR() throws Exception {
doThrow(InsufficientAccountBalanceException.class).when(accountService)
.transferWithChecks(1L, 2L, 1000.0);
MockHttpServletResponse response = mvc.perform(
post("/api/operations/transfer")
.param("sourceId", String.valueOf(1l))
.param("targetId", String.valueOf(2l))
.param("amount", String.valueOf(1000.0)))
.andReturn().getResponse();

assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
}
Loading