repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/config/ResourceServerConfig.java
|
package com.piggymetrics.account.config;
import com.piggymetrics.account.service.security.CustomUserInfoTokenServices;
import feign.RequestInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
/**
* @author cdov
*/
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
private final ResourceServerProperties sso;
@Autowired
public ResourceServerConfig(ResourceServerProperties sso) {
this.sso = sso;
}
@Bean
@ConfigurationProperties(prefix = "security.oauth2.client")
public ClientCredentialsResourceDetails clientCredentialsResourceDetails() {
return new ClientCredentialsResourceDetails();
}
@Bean
public RequestInterceptor oauth2FeignRequestInterceptor(){
return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), clientCredentialsResourceDetails());
}
@Bean
public OAuth2RestTemplate clientCredentialsRestTemplate() {
return new OAuth2RestTemplate(clientCredentialsResourceDetails());
}
@Bean
public ResourceServerTokenServices tokenServices() {
return new CustomUserInfoTokenServices(sso.getUserInfoUri(), sso.getClientId());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/" , "/demo").permitAll()
.anyRequest().authenticated();
}
}
| 2,483 | 39.721311 | 119 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/controller/AccountController.java
|
package com.piggymetrics.account.controller;
import com.piggymetrics.account.domain.Account;
import com.piggymetrics.account.domain.User;
import com.piggymetrics.account.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.security.Principal;
@RestController
public class AccountController {
@Autowired
private AccountService accountService;
@PreAuthorize("#oauth2.hasScope('server') or #name.equals('demo')")
@RequestMapping(path = "/{name}", method = RequestMethod.GET)
public Account getAccountByName(@PathVariable String name) {
return accountService.findByName(name);
}
@RequestMapping(path = "/current", method = RequestMethod.GET)
public Account getCurrentAccount(Principal principal) {
return accountService.findByName(principal.getName());
}
@RequestMapping(path = "/current", method = RequestMethod.PUT)
public void saveCurrentAccount(Principal principal, @Valid @RequestBody Account account) {
accountService.saveChanges(principal.getName(), account);
}
@RequestMapping(path = "/", method = RequestMethod.POST)
public Account createNewAccount(@Valid @RequestBody User user) {
return accountService.create(user);
}
}
| 1,350 | 32.775 | 91 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/controller/ErrorHandler.java
|
package com.piggymetrics.account.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class ErrorHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
// TODO add MethodArgumentNotValidException handler
// TODO remove such general handler
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void processValidationError(IllegalArgumentException e) {
log.info("Returning HTTP 400 Bad Request", e);
}
}
| 756 | 31.913043 | 65 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/domain/Account.java
|
package com.piggymetrics.account.domain;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.hibernate.validator.constraints.Length;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
@Document(collection = "accounts")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Account {
@Id
private String name;
private Date lastSeen;
@Valid
private List<Item> incomes;
@Valid
private List<Item> expenses;
@Valid
@NotNull
private Saving saving;
@Length(min = 0, max = 20_000)
private String note;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastSeen() {
return lastSeen;
}
public void setLastSeen(Date lastSeen) {
this.lastSeen = lastSeen;
}
public List<Item> getIncomes() {
return incomes;
}
public void setIncomes(List<Item> incomes) {
this.incomes = incomes;
}
public List<Item> getExpenses() {
return expenses;
}
public void setExpenses(List<Item> expenses) {
this.expenses = expenses;
}
public Saving getSaving() {
return saving;
}
public void setSaving(Saving saving) {
this.saving = saving;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
| 1,444 | 16.409639 | 62 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/domain/Currency.java
|
package com.piggymetrics.account.domain;
public enum Currency {
USD, EUR, RUB;
public static Currency getDefault() {
return USD;
}
}
| 141 | 11.909091 | 40 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/domain/Item.java
|
package com.piggymetrics.account.domain;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
public class Item {
@NotNull
@Length(min = 1, max = 20)
private String title;
@NotNull
private BigDecimal amount;
@NotNull
private Currency currency;
@NotNull
private TimePeriod period;
@NotNull
private String icon;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
public TimePeriod getPeriod() {
return period;
}
public void setPeriod(TimePeriod period) {
this.period = period;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
| 1,007 | 14.272727 | 50 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/domain/Saving.java
|
package com.piggymetrics.account.domain;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
public class Saving {
@NotNull
private BigDecimal amount;
@NotNull
private Currency currency;
@NotNull
private BigDecimal interest;
@NotNull
private Boolean deposit;
@NotNull
private Boolean capitalization;
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
public BigDecimal getInterest() {
return interest;
}
public void setInterest(BigDecimal interest) {
this.interest = interest;
}
public Boolean getDeposit() {
return deposit;
}
public void setDeposit(Boolean deposit) {
this.deposit = deposit;
}
public Boolean getCapitalization() {
return capitalization;
}
public void setCapitalization(Boolean capitalization) {
this.capitalization = capitalization;
}
}
| 1,033 | 15.412698 | 56 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/domain/TimePeriod.java
|
package com.piggymetrics.account.domain;
public enum TimePeriod {
YEAR, QUARTER, MONTH, DAY, HOUR
}
| 104 | 12.125 | 40 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/domain/User.java
|
package com.piggymetrics.account.domain;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotNull;
public class User {
@NotNull
@Length(min = 3, max = 20)
private String username;
@NotNull
@Length(min = 6, max = 40)
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| 552 | 15.757576 | 50 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/repository/AccountRepository.java
|
package com.piggymetrics.account.repository;
import com.piggymetrics.account.domain.Account;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface AccountRepository extends CrudRepository<Account, String> {
Account findByName(String name);
}
| 331 | 24.538462 | 76 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/service/AccountService.java
|
package com.piggymetrics.account.service;
import com.piggymetrics.account.domain.Account;
import com.piggymetrics.account.domain.User;
public interface AccountService {
/**
* Finds account by given name
*
* @param accountName
* @return found account
*/
Account findByName(String accountName);
/**
* Checks if account with the same name already exists
* Invokes Auth Service user creation
* Creates new account with default parameters
*
* @param user
* @return created account
*/
Account create(User user);
/**
* Validates and applies incoming account updates
* Invokes Statistics Service update
*
* @param name
* @param update
*/
void saveChanges(String name, Account update);
}
| 726 | 19.771429 | 55 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/service/AccountServiceImpl.java
|
package com.piggymetrics.account.service;
import com.piggymetrics.account.client.AuthServiceClient;
import com.piggymetrics.account.client.StatisticsServiceClient;
import com.piggymetrics.account.domain.Account;
import com.piggymetrics.account.domain.Currency;
import com.piggymetrics.account.domain.Saving;
import com.piggymetrics.account.domain.User;
import com.piggymetrics.account.repository.AccountRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.math.BigDecimal;
import java.util.Date;
@Service
public class AccountServiceImpl implements AccountService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private StatisticsServiceClient statisticsClient;
@Autowired
private AuthServiceClient authClient;
@Autowired
private AccountRepository repository;
/**
* {@inheritDoc}
*/
@Override
public Account findByName(String accountName) {
Assert.hasLength(accountName);
return repository.findByName(accountName);
}
/**
* {@inheritDoc}
*/
@Override
public Account create(User user) {
Account existing = repository.findByName(user.getUsername());
Assert.isNull(existing, "account already exists: " + user.getUsername());
authClient.createUser(user);
Saving saving = new Saving();
saving.setAmount(new BigDecimal(0));
saving.setCurrency(Currency.getDefault());
saving.setInterest(new BigDecimal(0));
saving.setDeposit(false);
saving.setCapitalization(false);
Account account = new Account();
account.setName(user.getUsername());
account.setLastSeen(new Date());
account.setSaving(saving);
repository.save(account);
log.info("new account has been created: " + account.getName());
return account;
}
/**
* {@inheritDoc}
*/
@Override
public void saveChanges(String name, Account update) {
Account account = repository.findByName(name);
Assert.notNull(account, "can't find account with name " + name);
account.setIncomes(update.getIncomes());
account.setExpenses(update.getExpenses());
account.setSaving(update.getSaving());
account.setNote(update.getNote());
account.setLastSeen(new Date());
repository.save(account);
log.debug("account {} changes has been saved", name);
statisticsClient.updateStatistics(name, account);
}
}
| 2,435 | 25.193548 | 75 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/service/security/CustomUserInfoTokenServices.java
|
package com.piggymetrics.account.service.security;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
import org.springframework.boot.autoconfigure.security.oauth2.resource.FixedAuthoritiesExtractor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import java.util.*;
/**
* Extended implementation of {@link org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices}
*
* By default, it designed to return only user details. This class provides {@link #getRequest(Map)} method, which
* returns clientId and scope of calling service. This information used in controller's security checks.
*/
public class CustomUserInfoTokenServices implements ResourceServerTokenServices {
protected final Log logger = LogFactory.getLog(getClass());
private static final String[] PRINCIPAL_KEYS = new String[] { "user", "username",
"userid", "user_id", "login", "id", "name" };
private final String userInfoEndpointUrl;
private final String clientId;
private OAuth2RestOperations restTemplate;
private String tokenType = DefaultOAuth2AccessToken.BEARER_TYPE;
private AuthoritiesExtractor authoritiesExtractor = new FixedAuthoritiesExtractor();
public CustomUserInfoTokenServices(String userInfoEndpointUrl, String clientId) {
this.userInfoEndpointUrl = userInfoEndpointUrl;
this.clientId = clientId;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public void setRestTemplate(OAuth2RestOperations restTemplate) {
this.restTemplate = restTemplate;
}
public void setAuthoritiesExtractor(AuthoritiesExtractor authoritiesExtractor) {
this.authoritiesExtractor = authoritiesExtractor;
}
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
throws AuthenticationException, InvalidTokenException {
Map<String, Object> map = getMap(this.userInfoEndpointUrl, accessToken);
if (map.containsKey("error")) {
this.logger.debug("userinfo returned error: " + map.get("error"));
throw new InvalidTokenException(accessToken);
}
return extractAuthentication(map);
}
private OAuth2Authentication extractAuthentication(Map<String, Object> map) {
Object principal = getPrincipal(map);
OAuth2Request request = getRequest(map);
List<GrantedAuthority> authorities = this.authoritiesExtractor
.extractAuthorities(map);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
principal, "N/A", authorities);
token.setDetails(map);
return new OAuth2Authentication(request, token);
}
private Object getPrincipal(Map<String, Object> map) {
for (String key : PRINCIPAL_KEYS) {
if (map.containsKey(key)) {
return map.get(key);
}
}
return "unknown";
}
@SuppressWarnings({ "unchecked" })
private OAuth2Request getRequest(Map<String, Object> map) {
Map<String, Object> request = (Map<String, Object>) map.get("oauth2Request");
String clientId = (String) request.get("clientId");
Set<String> scope = new LinkedHashSet<>(request.containsKey("scope") ?
(Collection<String>) request.get("scope") : Collections.<String>emptySet());
return new OAuth2Request(null, clientId, null, true, new HashSet<>(scope),
null, null, null, null);
}
@Override
public OAuth2AccessToken readAccessToken(String accessToken) {
throw new UnsupportedOperationException("Not supported: read access token");
}
@SuppressWarnings({ "unchecked" })
private Map<String, Object> getMap(String path, String accessToken) {
this.logger.debug("Getting user info from: " + path);
try {
OAuth2RestOperations restTemplate = this.restTemplate;
if (restTemplate == null) {
BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails();
resource.setClientId(this.clientId);
restTemplate = new OAuth2RestTemplate(resource);
}
OAuth2AccessToken existingToken = restTemplate.getOAuth2ClientContext()
.getAccessToken();
if (existingToken == null || !accessToken.equals(existingToken.getValue())) {
DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(
accessToken);
token.setTokenType(this.tokenType);
restTemplate.getOAuth2ClientContext().setAccessToken(token);
}
return restTemplate.getForEntity(path, Map.class).getBody();
}
catch (Exception ex) {
this.logger.info("Could not fetch user details: " + ex.getClass() + ", "
+ ex.getMessage());
return Collections.<String, Object>singletonMap("error",
"Could not fetch user details");
}
}
}
| 5,494 | 38.532374 | 123 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/test/java/com/piggymetrics/account/AccountServiceApplicationTests.java
|
package com.piggymetrics.account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AccountServiceApplicationTests {
@Test
public void contextLoads() {
}
}
| 350 | 18.5 | 60 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/test/java/com/piggymetrics/account/client/StatisticsServiceClientFallbackTest.java
|
package com.piggymetrics.account.client;
import com.piggymetrics.account.domain.Account;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.test.context.junit4.SpringRunner;
import static org.hamcrest.Matchers.containsString;
/**
* @author cdov
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {
"feign.hystrix.enabled=true"
})
public class StatisticsServiceClientFallbackTest {
@Autowired
private StatisticsServiceClient statisticsServiceClient;
@Rule
public final OutputCapture outputCapture = new OutputCapture();
@Before
public void setup() {
outputCapture.reset();
}
@Test
public void testUpdateStatisticsWithFailFallback(){
statisticsServiceClient.updateStatistics("test", new Account());
outputCapture.expect(containsString("Error during update statistics for account: test"));
}
}
| 1,146 | 25.068182 | 97 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/test/java/com/piggymetrics/account/controller/AccountControllerTest.java
|
package com.piggymetrics.account.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.piggymetrics.account.domain.*;
import com.piggymetrics.account.service.AccountService;
import com.sun.security.auth.UserPrincipal;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.math.BigDecimal;
import java.util.Date;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AccountControllerTest {
private static final ObjectMapper mapper = new ObjectMapper();
@InjectMocks
private AccountController accountController;
@Mock
private AccountService accountService;
private MockMvc mockMvc;
@Before
public void setup() {
initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
@Test
public void shouldGetAccountByName() throws Exception {
final Account account = new Account();
account.setName("test");
when(accountService.findByName(account.getName())).thenReturn(account);
mockMvc.perform(get("/" + account.getName()))
.andExpect(jsonPath("$.name").value(account.getName()))
.andExpect(status().isOk());
}
@Test
public void shouldGetCurrentAccount() throws Exception {
final Account account = new Account();
account.setName("test");
when(accountService.findByName(account.getName())).thenReturn(account);
mockMvc.perform(get("/current").principal(new UserPrincipal(account.getName())))
.andExpect(jsonPath("$.name").value(account.getName()))
.andExpect(status().isOk());
}
@Test
public void shouldSaveCurrentAccount() throws Exception {
Saving saving = new Saving();
saving.setAmount(new BigDecimal(1500));
saving.setCurrency(Currency.USD);
saving.setInterest(new BigDecimal("3.32"));
saving.setDeposit(true);
saving.setCapitalization(false);
Item grocery = new Item();
grocery.setTitle("Grocery");
grocery.setAmount(new BigDecimal(10));
grocery.setCurrency(Currency.USD);
grocery.setPeriod(TimePeriod.DAY);
grocery.setIcon("meal");
Item salary = new Item();
salary.setTitle("Salary");
salary.setAmount(new BigDecimal(9100));
salary.setCurrency(Currency.USD);
salary.setPeriod(TimePeriod.MONTH);
salary.setIcon("wallet");
final Account account = new Account();
account.setName("test");
account.setNote("test note");
account.setLastSeen(new Date());
account.setSaving(saving);
account.setExpenses(ImmutableList.of(grocery));
account.setIncomes(ImmutableList.of(salary));
String json = mapper.writeValueAsString(account);
mockMvc.perform(put("/current").principal(new UserPrincipal(account.getName())).contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isOk());
}
@Test
public void shouldFailOnValidationTryingToSaveCurrentAccount() throws Exception {
final Account account = new Account();
account.setName("test");
String json = mapper.writeValueAsString(account);
mockMvc.perform(put("/current").principal(new UserPrincipal(account.getName())).contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isBadRequest());
}
@Test
public void shouldRegisterNewAccount() throws Exception {
final User user = new User();
user.setUsername("test");
user.setPassword("password");
String json = mapper.writeValueAsString(user);
System.out.println(json);
mockMvc.perform(post("/").principal(new UserPrincipal("test")).contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isOk());
}
@Test
public void shouldFailOnValidationTryingToRegisterNewAccount() throws Exception {
final User user = new User();
user.setUsername("t");
String json = mapper.writeValueAsString(user);
mockMvc.perform(post("/").principal(new UserPrincipal("test")).contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isBadRequest());
}
}
| 4,620 | 30.013423 | 136 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/test/java/com/piggymetrics/account/repository/AccountRepositoryTest.java
|
package com.piggymetrics.account.repository;
import com.piggymetrics.account.domain.Account;
import com.piggymetrics.account.domain.Currency;
import com.piggymetrics.account.domain.Item;
import com.piggymetrics.account.domain.Saving;
import com.piggymetrics.account.domain.TimePeriod;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@DataMongoTest
public class AccountRepositoryTest {
@Autowired
private AccountRepository repository;
@Test
public void shouldFindAccountByName() {
Account stub = getStubAccount();
repository.save(stub);
Account found = repository.findByName(stub.getName());
assertEquals(stub.getLastSeen(), found.getLastSeen());
assertEquals(stub.getNote(), found.getNote());
assertEquals(stub.getIncomes().size(), found.getIncomes().size());
assertEquals(stub.getExpenses().size(), found.getExpenses().size());
}
private Account getStubAccount() {
Saving saving = new Saving();
saving.setAmount(new BigDecimal(1500));
saving.setCurrency(Currency.USD);
saving.setInterest(new BigDecimal("3.32"));
saving.setDeposit(true);
saving.setCapitalization(false);
Item vacation = new Item();
vacation.setTitle("Vacation");
vacation.setAmount(new BigDecimal(3400));
vacation.setCurrency(Currency.EUR);
vacation.setPeriod(TimePeriod.YEAR);
vacation.setIcon("tourism");
Item grocery = new Item();
grocery.setTitle("Grocery");
grocery.setAmount(new BigDecimal(10));
grocery.setCurrency(Currency.USD);
grocery.setPeriod(TimePeriod.DAY);
grocery.setIcon("meal");
Item salary = new Item();
salary.setTitle("Salary");
salary.setAmount(new BigDecimal(9100));
salary.setCurrency(Currency.USD);
salary.setPeriod(TimePeriod.MONTH);
salary.setIcon("wallet");
Account account = new Account();
account.setName("test");
account.setNote("test note");
account.setLastSeen(new Date());
account.setSaving(saving);
account.setExpenses(Arrays.asList(grocery, vacation));
account.setIncomes(Arrays.asList(salary));
return account;
}
}
| 2,380 | 28.395062 | 76 |
java
|
piggymetrics
|
piggymetrics-master/account-service/src/test/java/com/piggymetrics/account/service/AccountServiceTest.java
|
package com.piggymetrics.account.service;
import com.piggymetrics.account.client.AuthServiceClient;
import com.piggymetrics.account.client.StatisticsServiceClient;
import com.piggymetrics.account.domain.*;
import com.piggymetrics.account.repository.AccountRepository;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.math.BigDecimal;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
public class AccountServiceTest {
@InjectMocks
private AccountServiceImpl accountService;
@Mock
private StatisticsServiceClient statisticsClient;
@Mock
private AuthServiceClient authClient;
@Mock
private AccountRepository repository;
@Before
public void setup() {
initMocks(this);
}
@Test
public void shouldFindByName() {
final Account account = new Account();
account.setName("test");
when(accountService.findByName(account.getName())).thenReturn(account);
Account found = accountService.findByName(account.getName());
assertEquals(account, found);
}
@Test(expected = IllegalArgumentException.class)
public void shouldFailWhenNameIsEmpty() {
accountService.findByName("");
}
@Test
public void shouldCreateAccountWithGivenUser() {
User user = new User();
user.setUsername("test");
Account account = accountService.create(user);
assertEquals(user.getUsername(), account.getName());
assertEquals(0, account.getSaving().getAmount().intValue());
assertEquals(Currency.getDefault(), account.getSaving().getCurrency());
assertEquals(0, account.getSaving().getInterest().intValue());
assertEquals(false, account.getSaving().getDeposit());
assertEquals(false, account.getSaving().getCapitalization());
assertNotNull(account.getLastSeen());
verify(authClient, times(1)).createUser(user);
verify(repository, times(1)).save(account);
}
@Test
public void shouldSaveChangesWhenUpdatedAccountGiven() {
Item grocery = new Item();
grocery.setTitle("Grocery");
grocery.setAmount(new BigDecimal(10));
grocery.setCurrency(Currency.USD);
grocery.setPeriod(TimePeriod.DAY);
grocery.setIcon("meal");
Item salary = new Item();
salary.setTitle("Salary");
salary.setAmount(new BigDecimal(9100));
salary.setCurrency(Currency.USD);
salary.setPeriod(TimePeriod.MONTH);
salary.setIcon("wallet");
Saving saving = new Saving();
saving.setAmount(new BigDecimal(1500));
saving.setCurrency(Currency.USD);
saving.setInterest(new BigDecimal("3.32"));
saving.setDeposit(true);
saving.setCapitalization(false);
final Account update = new Account();
update.setName("test");
update.setNote("test note");
update.setIncomes(Arrays.asList(salary));
update.setExpenses(Arrays.asList(grocery));
update.setSaving(saving);
final Account account = new Account();
when(accountService.findByName("test")).thenReturn(account);
accountService.saveChanges("test", update);
assertEquals(update.getNote(), account.getNote());
assertNotNull(account.getLastSeen());
assertEquals(update.getSaving().getAmount(), account.getSaving().getAmount());
assertEquals(update.getSaving().getCurrency(), account.getSaving().getCurrency());
assertEquals(update.getSaving().getInterest(), account.getSaving().getInterest());
assertEquals(update.getSaving().getDeposit(), account.getSaving().getDeposit());
assertEquals(update.getSaving().getCapitalization(), account.getSaving().getCapitalization());
assertEquals(update.getExpenses().size(), account.getExpenses().size());
assertEquals(update.getIncomes().size(), account.getIncomes().size());
assertEquals(update.getExpenses().get(0).getTitle(), account.getExpenses().get(0).getTitle());
assertEquals(0, update.getExpenses().get(0).getAmount().compareTo(account.getExpenses().get(0).getAmount()));
assertEquals(update.getExpenses().get(0).getCurrency(), account.getExpenses().get(0).getCurrency());
assertEquals(update.getExpenses().get(0).getPeriod(), account.getExpenses().get(0).getPeriod());
assertEquals(update.getExpenses().get(0).getIcon(), account.getExpenses().get(0).getIcon());
assertEquals(update.getIncomes().get(0).getTitle(), account.getIncomes().get(0).getTitle());
assertEquals(0, update.getIncomes().get(0).getAmount().compareTo(account.getIncomes().get(0).getAmount()));
assertEquals(update.getIncomes().get(0).getCurrency(), account.getIncomes().get(0).getCurrency());
assertEquals(update.getIncomes().get(0).getPeriod(), account.getIncomes().get(0).getPeriod());
assertEquals(update.getIncomes().get(0).getIcon(), account.getIncomes().get(0).getIcon());
verify(repository, times(1)).save(account);
verify(statisticsClient, times(1)).updateStatistics("test", account);
}
@Test(expected = IllegalArgumentException.class)
public void shouldFailWhenNoAccountsExistedWithGivenName() {
final Account update = new Account();
update.setIncomes(Arrays.asList(new Item()));
update.setExpenses(Arrays.asList(new Item()));
when(accountService.findByName("test")).thenReturn(null);
accountService.saveChanges("test", update);
}
}
| 5,238 | 33.926667 | 111 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/main/java/com/piggymetrics/auth/AuthApplication.java
|
package com.piggymetrics.auth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
@SpringBootApplication
@EnableResourceServer
@EnableDiscoveryClient
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AuthApplication {
public static void main(String[] args) {
SpringApplication.run(AuthApplication.class, args);
}
}
| 683 | 33.2 | 102 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/main/java/com/piggymetrics/auth/config/OAuth2AuthorizationConfig.java
|
package com.piggymetrics.auth.config;
import com.piggymetrics.auth.service.security.MongoUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
/**
* @author cdov
*/
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
private TokenStore tokenStore = new InMemoryTokenStore();
private final String NOOP_PASSWORD_ENCODE = "{noop}";
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
private MongoUserDetailsService userDetailsService;
@Autowired
private Environment env;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// TODO persist clients details
// @formatter:off
clients.inMemory()
.withClient("browser")
.authorizedGrantTypes("refresh_token", "password")
.scopes("ui")
.and()
.withClient("account-service")
.secret(env.getProperty("ACCOUNT_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
.and()
.withClient("statistics-service")
.secret(env.getProperty("STATISTICS_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
.and()
.withClient("notification-service")
.secret(env.getProperty("NOTIFICATION_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server");
// @formatter:on
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(tokenStore)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
.passwordEncoder(NoOpPasswordEncoder.getInstance());
}
}
| 3,449 | 40.566265 | 116 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/main/java/com/piggymetrics/auth/config/WebSecurityConfig.java
|
package com.piggymetrics.auth.config;
import com.piggymetrics.auth.service.security.MongoUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* @author cdov
*/
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MongoUserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests().anyRequest().authenticated()
.and()
.csrf().disable();
// @formatter:on
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
| 1,563 | 35.372093 | 107 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/main/java/com/piggymetrics/auth/controller/UserController.java
|
package com.piggymetrics.auth.controller;
import com.piggymetrics.auth.domain.User;
import com.piggymetrics.auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.security.Principal;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/current", method = RequestMethod.GET)
public Principal getUser(Principal principal) {
return principal;
}
@PreAuthorize("#oauth2.hasScope('server')")
@RequestMapping(method = RequestMethod.POST)
public void createUser(@Valid @RequestBody User user) {
userService.create(user);
}
}
| 1,015 | 29.787879 | 64 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/main/java/com/piggymetrics/auth/domain/User.java
|
package com.piggymetrics.auth.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.List;
@Document(collection = "users")
public class User implements UserDetails {
@Id
private String username;
private String password;
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public List<GrantedAuthority> getAuthorities() {
return null;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
| 1,070 | 16.557377 | 65 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/main/java/com/piggymetrics/auth/repository/UserRepository.java
|
package com.piggymetrics.auth.repository;
import com.piggymetrics.auth.domain.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends CrudRepository<User, String> {
}
| 281 | 24.636364 | 70 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/main/java/com/piggymetrics/auth/service/UserService.java
|
package com.piggymetrics.auth.service;
import com.piggymetrics.auth.domain.User;
public interface UserService {
void create(User user);
}
| 143 | 13.4 | 41 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/main/java/com/piggymetrics/auth/service/UserServiceImpl.java
|
package com.piggymetrics.auth.service;
import com.piggymetrics.auth.domain.User;
import com.piggymetrics.auth.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.util.Optional;
@Service
public class UserServiceImpl implements UserService {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
@Autowired
private UserRepository repository;
@Override
public void create(User user) {
Optional<User> existing = repository.findById(user.getUsername());
existing.ifPresent(it-> {throw new IllegalArgumentException("user already exists: " + it.getUsername());});
String hash = encoder.encode(user.getPassword());
user.setPassword(hash);
repository.save(user);
log.info("new user has been created: {}", user.getUsername());
}
}
| 1,110 | 28.236842 | 109 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/main/java/com/piggymetrics/auth/service/security/MongoUserDetailsService.java
|
package com.piggymetrics.auth.service.security;
import com.piggymetrics.auth.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class MongoUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository repository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return repository.findById(username).orElseThrow(()->new UsernameNotFoundException(username));
}
}
| 768 | 33.954545 | 96 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/test/java/com/piggymetrics/auth/AuthServiceApplicationTests.java
|
package com.piggymetrics.auth;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AuthServiceApplicationTests {
@Test
public void contextLoads() {
}
}
| 343 | 19.235294 | 60 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/test/java/com/piggymetrics/auth/controller/UserControllerTest.java
|
package com.piggymetrics.auth.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.piggymetrics.auth.domain.User;
import com.piggymetrics.auth.service.UserService;
import com.sun.security.auth.UserPrincipal;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
private static final ObjectMapper mapper = new ObjectMapper();
@InjectMocks
private UserController accountController;
@Mock
private UserService userService;
private MockMvc mockMvc;
@Before
public void setup() {
initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
@Test
public void shouldCreateNewUser() throws Exception {
final User user = new User();
user.setUsername("test");
user.setPassword("password");
String json = mapper.writeValueAsString(user);
mockMvc.perform(post("/users").contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isOk());
}
@Test
public void shouldFailWhenUserIsNotValid() throws Exception {
final User user = new User();
user.setUsername("t");
user.setPassword("p");
mockMvc.perform(post("/users"))
.andExpect(status().isBadRequest());
}
@Test
public void shouldReturnCurrentUser() throws Exception {
mockMvc.perform(get("/users/current").principal(new UserPrincipal("test")))
.andExpect(jsonPath("$.name").value("test"))
.andExpect(status().isOk());
}
}
| 2,262 | 29.173333 | 89 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/test/java/com/piggymetrics/auth/repository/UserRepositoryTest.java
|
package com.piggymetrics.auth.repository;
import com.piggymetrics.auth.domain.User;
import com.piggymetrics.auth.service.security.MongoUserDetailsService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@DataMongoTest
public class UserRepositoryTest {
@Autowired
private UserRepository repository;
@Test
public void shouldSaveAndFindUserByName() {
User user = new User();
user.setUsername("name");
user.setPassword("password");
repository.save(user);
Optional<User> found = repository.findById(user.getUsername());
assertTrue(found.isPresent());
assertEquals(user.getUsername(), found.get().getUsername());
assertEquals(user.getPassword(), found.get().getPassword());
}
}
| 1,207 | 29.974359 | 92 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/test/java/com/piggymetrics/auth/service/UserServiceTest.java
|
package com.piggymetrics.auth.service;
import com.piggymetrics.auth.domain.User;
import com.piggymetrics.auth.repository.UserRepository;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.util.Optional;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
public class UserServiceTest {
@InjectMocks
private UserServiceImpl userService;
@Mock
private UserRepository repository;
@Before
public void setup() {
initMocks(this);
}
@Test
public void shouldCreateUser() {
User user = new User();
user.setUsername("name");
user.setPassword("password");
userService.create(user);
verify(repository, times(1)).save(user);
}
@Test(expected = IllegalArgumentException.class)
public void shouldFailWhenUserAlreadyExists() {
User user = new User();
user.setUsername("name");
user.setPassword("password");
when(repository.findById(user.getUsername())).thenReturn(Optional.of(new User()));
userService.create(user);
}
}
| 1,059 | 20.2 | 84 |
java
|
piggymetrics
|
piggymetrics-master/auth-service/src/test/java/com/piggymetrics/auth/service/security/MongoUserDetailsServiceTest.java
|
package com.piggymetrics.auth.service.security;
import com.piggymetrics.auth.domain.User;
import com.piggymetrics.auth.repository.UserRepository;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class MongoUserDetailsServiceTest {
@InjectMocks
private MongoUserDetailsService service;
@Mock
private UserRepository repository;
@Before
public void setup() {
initMocks(this);
}
@Test
public void shouldLoadByUsernameWhenUserExists() {
final User user = new User();
when(repository.findById(any())).thenReturn(Optional.of(user));
UserDetails loaded = service.loadUserByUsername("name");
assertEquals(user, loaded);
}
@Test(expected = UsernameNotFoundException.class)
public void shouldFailToLoadByUsernameWhenUserNotExists() {
service.loadUserByUsername("name");
}
}
| 1,216 | 24.893617 | 79 |
java
|
piggymetrics
|
piggymetrics-master/config/src/main/java/com/piggymetrics/config/ConfigApplication.java
|
package com.piggymetrics.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
| 402 | 25.866667 | 68 |
java
|
piggymetrics
|
piggymetrics-master/config/src/main/java/com/piggymetrics/config/SecurityConfig.java
|
package com.piggymetrics.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @author cdov
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http
.authorizeRequests()
.antMatchers("/actuator/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
;
}
}
| 721 | 27.88 | 101 |
java
|
piggymetrics
|
piggymetrics-master/gateway/src/main/java/com/piggymetrics/gateway/GatewayApplication.java
|
package com.piggymetrics.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
| 494 | 28.117647 | 72 |
java
|
piggymetrics
|
piggymetrics-master/gateway/src/test/java/com/piggymetrics/gateway/GatewayApplicationTests.java
|
package com.piggymetrics.gateway;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class GatewayApplicationTests {
@Test
public void contextLoads() {
}
@Test
public void fire() {
}
}
| 376 | 16.136364 | 60 |
java
|
piggymetrics
|
piggymetrics-master/monitoring/src/main/java/com/piggymetrics/monitoring/MonitoringApplication.java
|
package com.piggymetrics.monitoring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
@SpringBootApplication
@EnableHystrixDashboard
public class MonitoringApplication {
public static void main(String[] args) {
SpringApplication.run(MonitoringApplication.class, args);
}
}
| 434 | 28 | 82 |
java
|
piggymetrics
|
piggymetrics-master/monitoring/src/test/java/com/piggymetrics/monitoring/MonitoringApplicationTests.java
|
package com.piggymetrics.monitoring;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MonitoringApplicationTests {
@Test
public void contextLoads() {
}
}
| 348 | 19.529412 | 60 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/NotificationServiceApplication.java
|
package com.piggymetrics.notification;
import com.piggymetrics.notification.repository.converter.FrequencyReaderConverter;
import com.piggymetrics.notification.repository.converter.FrequencyWriterConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.convert.CustomConversions;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import java.util.Arrays;
@SpringBootApplication
@EnableDiscoveryClient
@EnableOAuth2Client
@EnableFeignClients
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableScheduling
public class NotificationServiceApplication {
public static void main(String[] args) {
SpringApplication.run(NotificationServiceApplication.class, args);
}
@Configuration
static class CustomConversionsConfig {
@Bean
public CustomConversions customConversions() {
return new CustomConversions(Arrays.asList(new FrequencyReaderConverter(),
new FrequencyWriterConverter()));
}
}
}
| 1,502 | 36.575 | 102 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/client/AccountServiceClient.java
|
package com.piggymetrics.notification.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(name = "account-service")
public interface AccountServiceClient {
@RequestMapping(method = RequestMethod.GET, value = "/accounts/{accountName}", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
String getAccount(@PathVariable("accountName") String accountName);
}
| 615 | 37.5 | 129 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/config/ResourceServerConfig.java
|
package com.piggymetrics.notification.config;
import feign.RequestInterceptor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
/**
* @author cdov
*/
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Bean
@ConfigurationProperties(prefix = "security.oauth2.client")
public ClientCredentialsResourceDetails clientCredentialsResourceDetails() {
return new ClientCredentialsResourceDetails();
}
@Bean
public RequestInterceptor oauth2FeignRequestInterceptor(){
return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), clientCredentialsResourceDetails());
}
@Bean
public OAuth2RestTemplate clientCredentialsRestTemplate() {
return new OAuth2RestTemplate(clientCredentialsResourceDetails());
}
}
| 1,537 | 42.942857 | 119 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/controller/RecipientController.java
|
package com.piggymetrics.notification.controller;
import com.piggymetrics.notification.domain.Recipient;
import com.piggymetrics.notification.service.RecipientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.security.Principal;
@RestController
@RequestMapping("/recipients")
public class RecipientController {
@Autowired
private RecipientService recipientService;
@RequestMapping(path = "/current", method = RequestMethod.GET)
public Object getCurrentNotificationsSettings(Principal principal) {
return recipientService.findByAccountName(principal.getName());
}
@RequestMapping(path = "/current", method = RequestMethod.PUT)
public Object saveCurrentNotificationsSettings(Principal principal, @Valid @RequestBody Recipient recipient) {
return recipientService.save(principal.getName(), recipient);
}
}
| 1,134 | 35.612903 | 111 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/domain/Frequency.java
|
package com.piggymetrics.notification.domain;
import java.util.stream.Stream;
public enum Frequency {
WEEKLY(7), MONTHLY(30), QUARTERLY(90);
private int days;
Frequency(int days) {
this.days = days;
}
public int getDays() {
return days;
}
public static Frequency withDays(int days) {
return Stream.of(Frequency.values())
.filter(f -> f.getDays() == days)
.findFirst()
.orElseThrow(IllegalArgumentException::new);
}
}
| 450 | 16.346154 | 48 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/domain/NotificationSettings.java
|
package com.piggymetrics.notification.domain;
import javax.validation.constraints.NotNull;
import java.util.Date;
public class NotificationSettings {
@NotNull
private Boolean active;
@NotNull
private Frequency frequency;
private Date lastNotified;
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Frequency getFrequency() {
return frequency;
}
public void setFrequency(Frequency frequency) {
this.frequency = frequency;
}
public Date getLastNotified() {
return lastNotified;
}
public void setLastNotified(Date lastNotified) {
this.lastNotified = lastNotified;
}
}
| 672 | 15.825 | 49 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/domain/NotificationType.java
|
package com.piggymetrics.notification.domain;
public enum NotificationType {
BACKUP("backup.email.subject", "backup.email.text", "backup.email.attachment"),
REMIND("remind.email.subject", "remind.email.text", null);
private String subject;
private String text;
private String attachment;
NotificationType(String subject, String text, String attachment) {
this.subject = subject;
this.text = text;
this.attachment = attachment;
}
public String getSubject() {
return subject;
}
public String getText() {
return text;
}
public String getAttachment() {
return attachment;
}
}
| 604 | 19.166667 | 80 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/domain/Recipient.java
|
package com.piggymetrics.notification.domain;
import org.hibernate.validator.constraints.Email;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Map;
@Document(collection = "recipients")
public class Recipient {
@Id
private String accountName;
@NotNull
@Email
private String email;
@Valid
private Map<NotificationType, NotificationSettings> scheduledNotifications;
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Map<NotificationType, NotificationSettings> getScheduledNotifications() {
return scheduledNotifications;
}
public void setScheduledNotifications(Map<NotificationType, NotificationSettings> scheduledNotifications) {
this.scheduledNotifications = scheduledNotifications;
}
@Override
public String toString() {
return "Recipient{" +
"accountName='" + accountName + '\'' +
", email='" + email + '\'' +
'}';
}
}
| 1,234 | 21.053571 | 108 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/repository/RecipientRepository.java
|
package com.piggymetrics.notification.repository;
import com.piggymetrics.notification.domain.Recipient;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface RecipientRepository extends CrudRepository<Recipient, String> {
Recipient findByAccountName(String name);
@Query("{ $and: [ {'scheduledNotifications.BACKUP.active': true }, { $where: 'this.scheduledNotifications.BACKUP.lastNotified < " +
"new Date(new Date().setDate(new Date().getDate() - this.scheduledNotifications.BACKUP.frequency ))' }] }")
List<Recipient> findReadyForBackup();
@Query("{ $and: [ {'scheduledNotifications.REMIND.active': true }, { $where: 'this.scheduledNotifications.REMIND.lastNotified < " +
"new Date(new Date().setDate(new Date().getDate() - this.scheduledNotifications.REMIND.frequency ))' }] }")
List<Recipient> findReadyForRemind();
}
| 1,006 | 40.958333 | 132 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/repository/converter/FrequencyReaderConverter.java
|
package com.piggymetrics.notification.repository.converter;
import com.piggymetrics.notification.domain.Frequency;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class FrequencyReaderConverter implements Converter<Integer, Frequency> {
@Override
public Frequency convert(Integer days) {
return Frequency.withDays(days);
}
}
| 413 | 26.6 | 80 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/repository/converter/FrequencyWriterConverter.java
|
package com.piggymetrics.notification.repository.converter;
import com.piggymetrics.notification.domain.Frequency;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class FrequencyWriterConverter implements Converter<Frequency, Integer> {
@Override
public Integer convert(Frequency frequency) {
return frequency.getDays();
}
}
| 413 | 26.6 | 80 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/service/EmailService.java
|
package com.piggymetrics.notification.service;
import com.piggymetrics.notification.domain.NotificationType;
import com.piggymetrics.notification.domain.Recipient;
import javax.mail.MessagingException;
import java.io.IOException;
public interface EmailService {
void send(NotificationType type, Recipient recipient, String attachment) throws MessagingException, IOException;
}
| 383 | 26.428571 | 113 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/service/EmailServiceImpl.java
|
package com.piggymetrics.notification.service;
import com.piggymetrics.notification.domain.NotificationType;
import com.piggymetrics.notification.domain.Recipient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.text.MessageFormat;
@Service
@RefreshScope
public class EmailServiceImpl implements EmailService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private JavaMailSender mailSender;
@Autowired
private Environment env;
@Override
public void send(NotificationType type, Recipient recipient, String attachment) throws MessagingException, IOException {
final String subject = env.getProperty(type.getSubject());
final String text = MessageFormat.format(env.getProperty(type.getText()), recipient.getAccountName());
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(recipient.getEmail());
helper.setSubject(subject);
helper.setText(text);
if (StringUtils.hasLength(attachment)) {
helper.addAttachment(env.getProperty(type.getAttachment()), new ByteArrayResource(attachment.getBytes()));
}
mailSender.send(message);
log.info("{} email notification has been send to {}", type, recipient.getEmail());
}
}
| 1,839 | 32.454545 | 121 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/service/NotificationService.java
|
package com.piggymetrics.notification.service;
public interface NotificationService {
void sendBackupNotifications();
void sendRemindNotifications();
}
| 157 | 16.555556 | 46 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/service/NotificationServiceImpl.java
|
package com.piggymetrics.notification.service;
import com.piggymetrics.notification.client.AccountServiceClient;
import com.piggymetrics.notification.domain.NotificationType;
import com.piggymetrics.notification.domain.Recipient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Service
public class NotificationServiceImpl implements NotificationService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private AccountServiceClient client;
@Autowired
private RecipientService recipientService;
@Autowired
private EmailService emailService;
@Override
@Scheduled(cron = "${backup.cron}")
public void sendBackupNotifications() {
final NotificationType type = NotificationType.BACKUP;
List<Recipient> recipients = recipientService.findReadyToNotify(type);
log.info("found {} recipients for backup notification", recipients.size());
recipients.forEach(recipient -> CompletableFuture.runAsync(() -> {
try {
String attachment = client.getAccount(recipient.getAccountName());
emailService.send(type, recipient, attachment);
recipientService.markNotified(type, recipient);
} catch (Throwable t) {
log.error("an error during backup notification for {}", recipient, t);
}
}));
}
@Override
@Scheduled(cron = "${remind.cron}")
public void sendRemindNotifications() {
final NotificationType type = NotificationType.REMIND;
List<Recipient> recipients = recipientService.findReadyToNotify(type);
log.info("found {} recipients for remind notification", recipients.size());
recipients.forEach(recipient -> CompletableFuture.runAsync(() -> {
try {
emailService.send(type, recipient, null);
recipientService.markNotified(type, recipient);
} catch (Throwable t) {
log.error("an error during remind notification for {}", recipient, t);
}
}));
}
}
| 2,099 | 29.882353 | 77 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/service/RecipientService.java
|
package com.piggymetrics.notification.service;
import com.piggymetrics.notification.domain.NotificationType;
import com.piggymetrics.notification.domain.Recipient;
import java.util.List;
public interface RecipientService {
/**
* Finds recipient by account name
*
* @param accountName
* @return recipient
*/
Recipient findByAccountName(String accountName);
/**
* Finds recipients, which are ready to be notified
* at the moment
*
* @param type
* @return recipients to notify
*/
List<Recipient> findReadyToNotify(NotificationType type);
/**
* Creates or updates recipient settings
*
* @param accountName
* @param recipient
* @return updated recipient
*/
Recipient save(String accountName, Recipient recipient);
/**
* Updates {@link NotificationType} {@code lastNotified} property with current date
* for given recipient.
*
* @param type
* @param recipient
*/
void markNotified(NotificationType type, Recipient recipient);
}
| 983 | 20.866667 | 84 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/main/java/com/piggymetrics/notification/service/RecipientServiceImpl.java
|
package com.piggymetrics.notification.service;
import com.piggymetrics.notification.domain.NotificationType;
import com.piggymetrics.notification.domain.Recipient;
import com.piggymetrics.notification.repository.RecipientRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.util.Date;
import java.util.List;
@Service
public class RecipientServiceImpl implements RecipientService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private RecipientRepository repository;
@Override
public Recipient findByAccountName(String accountName) {
Assert.hasLength(accountName);
return repository.findByAccountName(accountName);
}
/**
* {@inheritDoc}
*/
@Override
public Recipient save(String accountName, Recipient recipient) {
recipient.setAccountName(accountName);
recipient.getScheduledNotifications().values()
.forEach(settings -> {
if (settings.getLastNotified() == null) {
settings.setLastNotified(new Date());
}
});
repository.save(recipient);
log.info("recipient {} settings has been updated", recipient);
return recipient;
}
/**
* {@inheritDoc}
*/
@Override
public List<Recipient> findReadyToNotify(NotificationType type) {
switch (type) {
case BACKUP:
return repository.findReadyForBackup();
case REMIND:
return repository.findReadyForRemind();
default:
throw new IllegalArgumentException();
}
}
/**
* {@inheritDoc}
*/
@Override
public void markNotified(NotificationType type, Recipient recipient) {
recipient.getScheduledNotifications().get(type).setLastNotified(new Date());
repository.save(recipient);
}
}
| 1,823 | 23.648649 | 78 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/test/java/com/piggymetrics/notification/NotificationServiceApplicationTests.java
|
package com.piggymetrics.notification;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class NotificationServiceApplicationTests {
@Test
public void contextLoads() {
}
}
| 359 | 20.176471 | 60 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/test/java/com/piggymetrics/notification/controller/RecipientControllerTest.java
|
package com.piggymetrics.notification.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.piggymetrics.notification.domain.Frequency;
import com.piggymetrics.notification.domain.NotificationSettings;
import com.piggymetrics.notification.domain.NotificationType;
import com.piggymetrics.notification.domain.Recipient;
import com.piggymetrics.notification.service.RecipientService;
import com.sun.security.auth.UserPrincipal;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RecipientControllerTest {
private static final ObjectMapper mapper = new ObjectMapper();
@InjectMocks
private RecipientController recipientController;
@Mock
private RecipientService recipientService;
private MockMvc mockMvc;
@Before
public void setup() {
initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(recipientController).build();
}
@Test
public void shouldSaveCurrentRecipientSettings() throws Exception {
Recipient recipient = getStubRecipient();
String json = mapper.writeValueAsString(recipient);
mockMvc.perform(put("/recipients/current").principal(new UserPrincipal(recipient.getAccountName())).contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isOk());
}
@Test
public void shouldGetCurrentRecipientSettings() throws Exception {
Recipient recipient = getStubRecipient();
when(recipientService.findByAccountName(recipient.getAccountName())).thenReturn(recipient);
mockMvc.perform(get("/recipients/current").principal(new UserPrincipal(recipient.getAccountName())))
.andExpect(jsonPath("$.accountName").value(recipient.getAccountName()))
.andExpect(status().isOk());
}
private Recipient getStubRecipient() {
NotificationSettings remind = new NotificationSettings();
remind.setActive(true);
remind.setFrequency(Frequency.WEEKLY);
remind.setLastNotified(null);
NotificationSettings backup = new NotificationSettings();
backup.setActive(false);
backup.setFrequency(Frequency.MONTHLY);
backup.setLastNotified(null);
Recipient recipient = new Recipient();
recipient.setAccountName("test");
recipient.setEmail("[email protected]");
recipient.setScheduledNotifications(ImmutableMap.of(
NotificationType.BACKUP, backup,
NotificationType.REMIND, remind
));
return recipient;
}
}
| 3,235 | 34.173913 | 156 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/test/java/com/piggymetrics/notification/repository/RecipientRepositoryTest.java
|
package com.piggymetrics.notification.repository;
import com.google.common.collect.ImmutableMap;
import com.piggymetrics.notification.domain.Frequency;
import com.piggymetrics.notification.domain.NotificationSettings;
import com.piggymetrics.notification.domain.NotificationType;
import com.piggymetrics.notification.domain.Recipient;
import org.apache.commons.lang.time.DateUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@DataMongoTest
public class RecipientRepositoryTest {
@Autowired
private RecipientRepository repository;
@Test
public void shouldFindByAccountName() {
NotificationSettings remind = new NotificationSettings();
remind.setActive(true);
remind.setFrequency(Frequency.WEEKLY);
remind.setLastNotified(new Date(0));
NotificationSettings backup = new NotificationSettings();
backup.setActive(false);
backup.setFrequency(Frequency.MONTHLY);
backup.setLastNotified(new Date());
Recipient recipient = new Recipient();
recipient.setAccountName("test");
recipient.setEmail("[email protected]");
recipient.setScheduledNotifications(ImmutableMap.of(
NotificationType.BACKUP, backup,
NotificationType.REMIND, remind
));
repository.save(recipient);
Recipient found = repository.findByAccountName(recipient.getAccountName());
assertEquals(recipient.getAccountName(), found.getAccountName());
assertEquals(recipient.getEmail(), found.getEmail());
assertEquals(recipient.getScheduledNotifications().get(NotificationType.BACKUP).getActive(),
found.getScheduledNotifications().get(NotificationType.BACKUP).getActive());
assertEquals(recipient.getScheduledNotifications().get(NotificationType.BACKUP).getFrequency(),
found.getScheduledNotifications().get(NotificationType.BACKUP).getFrequency());
assertEquals(recipient.getScheduledNotifications().get(NotificationType.BACKUP).getLastNotified(),
found.getScheduledNotifications().get(NotificationType.BACKUP).getLastNotified());
assertEquals(recipient.getScheduledNotifications().get(NotificationType.REMIND).getActive(),
found.getScheduledNotifications().get(NotificationType.REMIND).getActive());
assertEquals(recipient.getScheduledNotifications().get(NotificationType.REMIND).getFrequency(),
found.getScheduledNotifications().get(NotificationType.REMIND).getFrequency());
assertEquals(recipient.getScheduledNotifications().get(NotificationType.REMIND).getLastNotified(),
found.getScheduledNotifications().get(NotificationType.REMIND).getLastNotified());
}
@Test
public void shouldFindReadyForRemindWhenFrequencyIsWeeklyAndLastNotifiedWas8DaysAgo() {
NotificationSettings remind = new NotificationSettings();
remind.setActive(true);
remind.setFrequency(Frequency.WEEKLY);
remind.setLastNotified(DateUtils.addDays(new Date(), -8));
Recipient recipient = new Recipient();
recipient.setAccountName("test");
recipient.setEmail("[email protected]");
recipient.setScheduledNotifications(ImmutableMap.of(
NotificationType.REMIND, remind
));
repository.save(recipient);
List<Recipient> found = repository.findReadyForRemind();
assertFalse(found.isEmpty());
}
@Test
public void shouldNotFindReadyForRemindWhenFrequencyIsWeeklyAndLastNotifiedWasYesterday() {
NotificationSettings remind = new NotificationSettings();
remind.setActive(true);
remind.setFrequency(Frequency.WEEKLY);
remind.setLastNotified(DateUtils.addDays(new Date(), -1));
Recipient recipient = new Recipient();
recipient.setAccountName("test");
recipient.setEmail("[email protected]");
recipient.setScheduledNotifications(ImmutableMap.of(
NotificationType.REMIND, remind
));
repository.save(recipient);
List<Recipient> found = repository.findReadyForRemind();
assertTrue(found.isEmpty());
}
@Test
public void shouldNotFindReadyForRemindWhenNotificationIsNotActive() {
NotificationSettings remind = new NotificationSettings();
remind.setActive(false);
remind.setFrequency(Frequency.WEEKLY);
remind.setLastNotified(DateUtils.addDays(new Date(), -30));
Recipient recipient = new Recipient();
recipient.setAccountName("test");
recipient.setEmail("[email protected]");
recipient.setScheduledNotifications(ImmutableMap.of(
NotificationType.REMIND, remind
));
repository.save(recipient);
List<Recipient> found = repository.findReadyForRemind();
assertTrue(found.isEmpty());
}
@Test
public void shouldNotFindReadyForBackupWhenFrequencyIsQuaterly() {
NotificationSettings remind = new NotificationSettings();
remind.setActive(true);
remind.setFrequency(Frequency.QUARTERLY);
remind.setLastNotified(DateUtils.addDays(new Date(), -91));
Recipient recipient = new Recipient();
recipient.setAccountName("test");
recipient.setEmail("[email protected]");
recipient.setScheduledNotifications(ImmutableMap.of(
NotificationType.BACKUP, remind
));
repository.save(recipient);
List<Recipient> found = repository.findReadyForBackup();
assertFalse(found.isEmpty());
}
}
| 5,399 | 34.064935 | 100 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/test/java/com/piggymetrics/notification/service/EmailServiceImplTest.java
|
package com.piggymetrics.notification.service;
import com.piggymetrics.notification.domain.NotificationType;
import com.piggymetrics.notification.domain.Recipient;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSender;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class EmailServiceImplTest {
@InjectMocks
private EmailServiceImpl emailService;
@Mock
private JavaMailSender mailSender;
@Mock
private Environment env;
@Captor
private ArgumentCaptor<MimeMessage> captor;
@Before
public void setup() {
initMocks(this);
when(mailSender.createMimeMessage())
.thenReturn(new MimeMessage(Session.getDefaultInstance(new Properties())));
}
@Test
public void shouldSendBackupEmail() throws MessagingException, IOException {
final String subject = "subject";
final String text = "text";
final String attachment = "attachment.json";
Recipient recipient = new Recipient();
recipient.setAccountName("test");
recipient.setEmail("[email protected]");
when(env.getProperty(NotificationType.BACKUP.getSubject())).thenReturn(subject);
when(env.getProperty(NotificationType.BACKUP.getText())).thenReturn(text);
when(env.getProperty(NotificationType.BACKUP.getAttachment())).thenReturn(attachment);
emailService.send(NotificationType.BACKUP, recipient, "{\"name\":\"test\"");
verify(mailSender).send(captor.capture());
MimeMessage message = captor.getValue();
assertEquals(subject, message.getSubject());
// TODO check other fields
}
@Test
public void shouldSendRemindEmail() throws MessagingException, IOException {
final String subject = "subject";
final String text = "text";
Recipient recipient = new Recipient();
recipient.setAccountName("test");
recipient.setEmail("[email protected]");
when(env.getProperty(NotificationType.REMIND.getSubject())).thenReturn(subject);
when(env.getProperty(NotificationType.REMIND.getText())).thenReturn(text);
emailService.send(NotificationType.REMIND, recipient, null);
verify(mailSender).send(captor.capture());
MimeMessage message = captor.getValue();
assertEquals(subject, message.getSubject());
// TODO check other fields
}
}
| 2,665 | 28.296703 | 88 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/test/java/com/piggymetrics/notification/service/NotificationServiceImplTest.java
|
package com.piggymetrics.notification.service;
import com.google.common.collect.ImmutableList;
import com.piggymetrics.notification.client.AccountServiceClient;
import com.piggymetrics.notification.domain.NotificationType;
import com.piggymetrics.notification.domain.Recipient;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import javax.mail.MessagingException;
import java.io.IOException;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
public class NotificationServiceImplTest {
@InjectMocks
private NotificationServiceImpl notificationService;
@Mock
private RecipientService recipientService;
@Mock
private AccountServiceClient client;
@Mock
private EmailService emailService;
@Before
public void setup() {
initMocks(this);
}
@Test
public void shouldSendBackupNotificationsEvenWhenErrorsOccursForSomeRecipients() throws IOException, MessagingException, InterruptedException {
final String attachment = "json";
Recipient withError = new Recipient();
withError.setAccountName("with-error");
Recipient withNoError = new Recipient();
withNoError.setAccountName("with-no-error");
when(client.getAccount(withError.getAccountName())).thenThrow(new RuntimeException());
when(client.getAccount(withNoError.getAccountName())).thenReturn(attachment);
when(recipientService.findReadyToNotify(NotificationType.BACKUP)).thenReturn(ImmutableList.of(withNoError, withError));
notificationService.sendBackupNotifications();
// TODO test concurrent code in a right way
verify(emailService, timeout(100)).send(NotificationType.BACKUP, withNoError, attachment);
verify(recipientService, timeout(100)).markNotified(NotificationType.BACKUP, withNoError);
verify(recipientService, never()).markNotified(NotificationType.BACKUP, withError);
}
@Test
public void shouldSendRemindNotificationsEvenWhenErrorsOccursForSomeRecipients() throws IOException, MessagingException, InterruptedException {
final String attachment = "json";
Recipient withError = new Recipient();
withError.setAccountName("with-error");
Recipient withNoError = new Recipient();
withNoError.setAccountName("with-no-error");
when(recipientService.findReadyToNotify(NotificationType.REMIND)).thenReturn(ImmutableList.of(withNoError, withError));
doThrow(new RuntimeException()).when(emailService).send(NotificationType.REMIND, withError, null);
notificationService.sendRemindNotifications();
// TODO test concurrent code in a right way
verify(emailService, timeout(100)).send(NotificationType.REMIND, withNoError, null);
verify(recipientService, timeout(100)).markNotified(NotificationType.REMIND, withNoError);
verify(recipientService, never()).markNotified(NotificationType.REMIND, withError);
}
}
| 2,845 | 32.093023 | 144 |
java
|
piggymetrics
|
piggymetrics-master/notification-service/src/test/java/com/piggymetrics/notification/service/RecipientServiceImplTest.java
|
package com.piggymetrics.notification.service;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.piggymetrics.notification.domain.Frequency;
import com.piggymetrics.notification.domain.NotificationSettings;
import com.piggymetrics.notification.domain.NotificationType;
import com.piggymetrics.notification.domain.Recipient;
import com.piggymetrics.notification.repository.RecipientRepository;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class RecipientServiceImplTest {
@InjectMocks
private RecipientServiceImpl recipientService;
@Mock
private RecipientRepository repository;
@Before
public void setup() {
initMocks(this);
}
@Test
public void shouldFindByAccountName() {
Recipient recipient = new Recipient();
recipient.setAccountName("test");
when(repository.findByAccountName(recipient.getAccountName())).thenReturn(recipient);
Recipient found = recipientService.findByAccountName(recipient.getAccountName());
assertEquals(recipient, found);
}
@Test(expected = IllegalArgumentException.class)
public void shouldFailToFindRecipientWhenAccountNameIsEmpty() {
recipientService.findByAccountName("");
}
@Test
public void shouldSaveRecipient() {
NotificationSettings remind = new NotificationSettings();
remind.setActive(true);
remind.setFrequency(Frequency.WEEKLY);
remind.setLastNotified(null);
NotificationSettings backup = new NotificationSettings();
backup.setActive(false);
backup.setFrequency(Frequency.MONTHLY);
backup.setLastNotified(new Date());
Recipient recipient = new Recipient();
recipient.setEmail("[email protected]");
recipient.setScheduledNotifications(ImmutableMap.of(
NotificationType.BACKUP, backup,
NotificationType.REMIND, remind
));
Recipient saved = recipientService.save("test", recipient);
verify(repository).save(recipient);
assertNotNull(saved.getScheduledNotifications().get(NotificationType.REMIND).getLastNotified());
assertEquals("test", saved.getAccountName());
}
@Test
public void shouldFindReadyToNotifyWhenNotificationTypeIsBackup() {
final List<Recipient> recipients = ImmutableList.of(new Recipient());
when(repository.findReadyForBackup()).thenReturn(recipients);
List<Recipient> found = recipientService.findReadyToNotify(NotificationType.BACKUP);
assertEquals(recipients, found);
}
@Test
public void shouldFindReadyToNotifyWhenNotificationTypeIsRemind() {
final List<Recipient> recipients = ImmutableList.of(new Recipient());
when(repository.findReadyForRemind()).thenReturn(recipients);
List<Recipient> found = recipientService.findReadyToNotify(NotificationType.REMIND);
assertEquals(recipients, found);
}
@Test
public void shouldMarkAsNotified() {
NotificationSettings remind = new NotificationSettings();
remind.setActive(true);
remind.setFrequency(Frequency.WEEKLY);
remind.setLastNotified(null);
Recipient recipient = new Recipient();
recipient.setAccountName("test");
recipient.setEmail("[email protected]");
recipient.setScheduledNotifications(ImmutableMap.of(
NotificationType.REMIND, remind
));
recipientService.markNotified(NotificationType.REMIND, recipient);
assertNotNull(recipient.getScheduledNotifications().get(NotificationType.REMIND).getLastNotified());
verify(repository).save(recipient);
}
}
| 3,691 | 30.555556 | 102 |
java
|
piggymetrics
|
piggymetrics-master/registry/src/main/java/com/piggymetrics/registry/RegistryApplication.java
|
package com.piggymetrics.registry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class RegistryApplication {
public static void main(String[] args) {
SpringApplication.run(RegistryApplication.class, args);
}
}
| 416 | 26.8 | 74 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/StatisticsApplication.java
|
package com.piggymetrics.statistics;
import com.piggymetrics.statistics.repository.converter.DataPointIdReaderConverter;
import com.piggymetrics.statistics.repository.converter.DataPointIdWriterConverter;
import com.piggymetrics.statistics.service.security.CustomUserInfoTokenServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.convert.CustomConversions;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import java.util.Arrays;
@SpringBootApplication
@EnableDiscoveryClient
@EnableOAuth2Client
@EnableFeignClients
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class StatisticsApplication {
public static void main(String[] args) {
SpringApplication.run(StatisticsApplication.class, args);
}
@Configuration
static class CustomConversionsConfig {
@Bean
public CustomConversions customConversions() {
return new CustomConversions(Arrays.asList(new DataPointIdReaderConverter(),
new DataPointIdWriterConverter()));
}
}
}
| 1,729 | 40.190476 | 102 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/client/ExchangeRatesClient.java
|
package com.piggymetrics.statistics.client;
import com.piggymetrics.statistics.domain.Currency;
import com.piggymetrics.statistics.domain.ExchangeRatesContainer;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(url = "${rates.url}", name = "rates-client", fallback = ExchangeRatesClientFallback.class)
public interface ExchangeRatesClient {
@RequestMapping(method = RequestMethod.GET, value = "/latest")
ExchangeRatesContainer getRates(@RequestParam("base") Currency base);
}
| 694 | 39.882353 | 103 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/client/ExchangeRatesClientFallback.java
|
package com.piggymetrics.statistics.client;
import com.piggymetrics.statistics.domain.Currency;
import com.piggymetrics.statistics.domain.ExchangeRatesContainer;
import org.springframework.stereotype.Component;
import java.util.Collections;
@Component
public class ExchangeRatesClientFallback implements ExchangeRatesClient {
@Override
public ExchangeRatesContainer getRates(Currency base) {
ExchangeRatesContainer container = new ExchangeRatesContainer();
container.setBase(Currency.getBase());
container.setRates(Collections.emptyMap());
return container;
}
}
| 610 | 29.55 | 73 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/config/ResourceServerConfig.java
|
package com.piggymetrics.statistics.config;
import com.piggymetrics.statistics.service.security.CustomUserInfoTokenServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
/**
* @author cdov
*/
@EnableResourceServer
@Configuration
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
private ResourceServerProperties sso;
@Bean
public ResourceServerTokenServices tokenServices() {
return new CustomUserInfoTokenServices(sso.getUserInfoUri(), sso.getClientId());
}
}
| 1,059 | 39.769231 | 111 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/controller/StatisticsController.java
|
package com.piggymetrics.statistics.controller;
import com.piggymetrics.statistics.domain.Account;
import com.piggymetrics.statistics.domain.timeseries.DataPoint;
import com.piggymetrics.statistics.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.security.Principal;
import java.util.List;
@RestController
public class StatisticsController {
@Autowired
private StatisticsService statisticsService;
@RequestMapping(value = "/current", method = RequestMethod.GET)
public List<DataPoint> getCurrentAccountStatistics(Principal principal) {
return statisticsService.findByAccountName(principal.getName());
}
@PreAuthorize("#oauth2.hasScope('server') or #accountName.equals('demo')")
@RequestMapping(value = "/{accountName}", method = RequestMethod.GET)
public List<DataPoint> getStatisticsByAccountName(@PathVariable String accountName) {
return statisticsService.findByAccountName(accountName);
}
@PreAuthorize("#oauth2.hasScope('server')")
@RequestMapping(value = "/{accountName}", method = RequestMethod.PUT)
public void saveAccountStatistics(@PathVariable String accountName, @Valid @RequestBody Account account) {
statisticsService.save(accountName, account);
}
}
| 1,389 | 36.567568 | 107 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/domain/Account.java
|
package com.piggymetrics.statistics.domain;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
@Document(collection = "accounts")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Account {
@Valid
@NotNull
private List<Item> incomes;
@Valid
@NotNull
private List<Item> expenses;
@Valid
@NotNull
private Saving saving;
public List<Item> getIncomes() {
return incomes;
}
public void setIncomes(List<Item> incomes) {
this.incomes = incomes;
}
public List<Item> getExpenses() {
return expenses;
}
public void setExpenses(List<Item> expenses) {
this.expenses = expenses;
}
public Saving getSaving() {
return saving;
}
public void setSaving(Saving saving) {
this.saving = saving;
}
}
| 900 | 17.02 | 62 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/domain/Currency.java
|
package com.piggymetrics.statistics.domain;
public enum Currency {
USD, EUR, RUB;
public static Currency getBase() {
return USD;
}
}
| 141 | 11.909091 | 43 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/domain/ExchangeRatesContainer.java
|
package com.piggymetrics.statistics.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true, value = {"date"})
public class ExchangeRatesContainer {
private LocalDate date = LocalDate.now();
private Currency base;
private Map<String, BigDecimal> rates;
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Currency getBase() {
return base;
}
public void setBase(Currency base) {
this.base = base;
}
public Map<String, BigDecimal> getRates() {
return rates;
}
public void setRates(Map<String, BigDecimal> rates) {
this.rates = rates;
}
@Override
public String toString() {
return "RateList{" +
"date=" + date +
", base=" + base +
", rates=" + rates +
'}';
}
}
| 912 | 16.901961 | 61 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/domain/Item.java
|
package com.piggymetrics.statistics.domain;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
public class Item {
@NotNull
@Length(min = 1, max = 20)
private String title;
@NotNull
private BigDecimal amount;
@NotNull
private Currency currency;
@NotNull
private TimePeriod period;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
public TimePeriod getPeriod() {
return period;
}
public void setPeriod(TimePeriod period) {
this.period = period;
}
}
| 871 | 14.854545 | 50 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/domain/Saving.java
|
package com.piggymetrics.statistics.domain;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
public class Saving {
@NotNull
private BigDecimal amount;
@NotNull
private Currency currency;
@NotNull
private BigDecimal interest;
@NotNull
private Boolean deposit;
@NotNull
private Boolean capitalization;
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
public BigDecimal getInterest() {
return interest;
}
public void setInterest(BigDecimal interest) {
this.interest = interest;
}
public Boolean getDeposit() {
return deposit;
}
public void setDeposit(Boolean deposit) {
this.deposit = deposit;
}
public Boolean getCapitalization() {
return capitalization;
}
public void setCapitalization(Boolean capitalization) {
this.capitalization = capitalization;
}
}
| 1,036 | 15.460317 | 56 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/domain/TimePeriod.java
|
package com.piggymetrics.statistics.domain;
import java.math.BigDecimal;
public enum TimePeriod {
YEAR(365.2425), QUARTER(91.3106), MONTH(30.4368), DAY(1), HOUR(0.0416);
private double baseRatio;
TimePeriod(double baseRatio) {
this.baseRatio = baseRatio;
}
public BigDecimal getBaseRatio() {
return new BigDecimal(baseRatio);
}
public static TimePeriod getBase() {
return DAY;
}
}
| 402 | 16.521739 | 72 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/domain/timeseries/DataPoint.java
|
package com.piggymetrics.statistics.domain.timeseries;
import com.piggymetrics.statistics.domain.Currency;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Set;
/**
* Represents daily time series data point containing
* current account state
*/
@Document(collection = "datapoints")
public class DataPoint {
@Id
private DataPointId id;
private Set<ItemMetric> incomes;
private Set<ItemMetric> expenses;
private Map<StatisticMetric, BigDecimal> statistics;
private Map<Currency, BigDecimal> rates;
public DataPointId getId() {
return id;
}
public void setId(DataPointId id) {
this.id = id;
}
public Set<ItemMetric> getIncomes() {
return incomes;
}
public void setIncomes(Set<ItemMetric> incomes) {
this.incomes = incomes;
}
public Set<ItemMetric> getExpenses() {
return expenses;
}
public void setExpenses(Set<ItemMetric> expenses) {
this.expenses = expenses;
}
public Map<StatisticMetric, BigDecimal> getStatistics() {
return statistics;
}
public void setStatistics(Map<StatisticMetric, BigDecimal> statistics) {
this.statistics = statistics;
}
public Map<Currency, BigDecimal> getRates() {
return rates;
}
public void setRates(Map<Currency, BigDecimal> rates) {
this.rates = rates;
}
}
| 1,382 | 19.043478 | 73 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/domain/timeseries/DataPointId.java
|
package com.piggymetrics.statistics.domain.timeseries;
import java.io.Serializable;
import java.util.Date;
public class DataPointId implements Serializable {
private static final long serialVersionUID = 1L;
private String account;
private Date date;
public DataPointId(String account, Date date) {
this.account = account;
this.date = date;
}
public String getAccount() {
return account;
}
public Date getDate() {
return date;
}
@Override
public String toString() {
return "DataPointId{" +
"account='" + account + '\'' +
", date=" + date +
'}';
}
}
| 591 | 15.914286 | 54 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/domain/timeseries/ItemMetric.java
|
package com.piggymetrics.statistics.domain.timeseries;
import com.piggymetrics.statistics.domain.Currency;
import com.piggymetrics.statistics.domain.TimePeriod;
import java.math.BigDecimal;
/**
* Represents normalized {@link com.piggymetrics.statistics.domain.Item} object
* with {@link Currency#getBase()} currency and {@link TimePeriod#getBase()} time period
*/
public class ItemMetric {
private String title;
private BigDecimal amount;
public ItemMetric(String title, BigDecimal amount) {
this.title = title;
this.amount = amount;
}
public String getTitle() {
return title;
}
public BigDecimal getAmount() {
return amount;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ItemMetric that = (ItemMetric) o;
return title.equalsIgnoreCase(that.title);
}
@Override
public int hashCode() {
return title.hashCode();
}
}
| 949 | 19.212766 | 88 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/domain/timeseries/StatisticMetric.java
|
package com.piggymetrics.statistics.domain.timeseries;
public enum StatisticMetric {
INCOMES_AMOUNT, EXPENSES_AMOUNT, SAVING_AMOUNT
}
| 138 | 16.375 | 54 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/repository/DataPointRepository.java
|
package com.piggymetrics.statistics.repository;
import com.piggymetrics.statistics.domain.timeseries.DataPoint;
import com.piggymetrics.statistics.domain.timeseries.DataPointId;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface DataPointRepository extends CrudRepository<DataPoint, DataPointId> {
List<DataPoint> findByIdAccount(String account);
}
| 465 | 28.125 | 85 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/repository/converter/DataPointIdReaderConverter.java
|
package com.piggymetrics.statistics.repository.converter;
import com.mongodb.DBObject;
import com.piggymetrics.statistics.domain.timeseries.DataPointId;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class DataPointIdReaderConverter implements Converter<DBObject, DataPointId> {
@Override
public DataPointId convert(DBObject object) {
Date date = (Date) object.get("date");
String account = (String) object.get("account");
return new DataPointId(account, date);
}
}
| 585 | 25.636364 | 85 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/repository/converter/DataPointIdWriterConverter.java
|
package com.piggymetrics.statistics.repository.converter;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.piggymetrics.statistics.domain.timeseries.DataPointId;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class DataPointIdWriterConverter implements Converter<DataPointId, DBObject> {
private static final int FIELDS = 2;
@Override
public DBObject convert(DataPointId id) {
DBObject object = new BasicDBObject(FIELDS);
object.put("date", id.getDate());
object.put("account", id.getAccount());
return object;
}
}
| 640 | 24.64 | 85 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/service/ExchangeRatesService.java
|
package com.piggymetrics.statistics.service;
import com.piggymetrics.statistics.domain.Currency;
import java.math.BigDecimal;
import java.util.Map;
public interface ExchangeRatesService {
/**
* Requests today's foreign exchange rates from a provider
* or reuses values from the last request (if they are still relevant)
*
* @return current date rates
*/
Map<Currency, BigDecimal> getCurrentRates();
/**
* Converts given amount to specified currency
*
* @param from {@link Currency}
* @param to {@link Currency}
* @param amount to be converted
* @return converted amount
*/
BigDecimal convert(Currency from, Currency to, BigDecimal amount);
}
| 675 | 23.142857 | 71 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/service/ExchangeRatesServiceImpl.java
|
package com.piggymetrics.statistics.service;
import com.google.common.collect.ImmutableMap;
import com.piggymetrics.statistics.client.ExchangeRatesClient;
import com.piggymetrics.statistics.domain.Currency;
import com.piggymetrics.statistics.domain.ExchangeRatesContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.Map;
@Service
public class ExchangeRatesServiceImpl implements ExchangeRatesService {
private static final Logger log = LoggerFactory.getLogger(ExchangeRatesServiceImpl.class);
private ExchangeRatesContainer container;
@Autowired
private ExchangeRatesClient client;
/**
* {@inheritDoc}
*/
@Override
public Map<Currency, BigDecimal> getCurrentRates() {
if (container == null || !container.getDate().equals(LocalDate.now())) {
container = client.getRates(Currency.getBase());
log.info("exchange rates has been updated: {}", container);
}
return ImmutableMap.of(
Currency.EUR, container.getRates().get(Currency.EUR.name()),
Currency.RUB, container.getRates().get(Currency.RUB.name()),
Currency.USD, BigDecimal.ONE
);
}
/**
* {@inheritDoc}
*/
@Override
public BigDecimal convert(Currency from, Currency to, BigDecimal amount) {
Assert.notNull(amount);
Map<Currency, BigDecimal> rates = getCurrentRates();
BigDecimal ratio = rates.get(to).divide(rates.get(from), 4, RoundingMode.HALF_UP);
return amount.multiply(ratio);
}
}
| 1,671 | 26.866667 | 91 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/service/StatisticsService.java
|
package com.piggymetrics.statistics.service;
import com.piggymetrics.statistics.domain.Account;
import com.piggymetrics.statistics.domain.timeseries.DataPoint;
import java.util.List;
public interface StatisticsService {
/**
* Finds account by given name
*
* @param accountName
* @return found account
*/
List<DataPoint> findByAccountName(String accountName);
/**
* Converts given {@link Account} object to {@link DataPoint} with
* a set of significant statistic metrics.
*
* Compound {@link DataPoint#id} forces to rewrite the object
* for each account within a day.
*
* @param accountName
* @param account
*/
DataPoint save(String accountName, Account account);
}
| 703 | 21.709677 | 67 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/service/StatisticsServiceImpl.java
|
package com.piggymetrics.statistics.service;
import com.google.common.collect.ImmutableMap;
import com.piggymetrics.statistics.domain.*;
import com.piggymetrics.statistics.domain.timeseries.DataPoint;
import com.piggymetrics.statistics.domain.timeseries.DataPointId;
import com.piggymetrics.statistics.domain.timeseries.ItemMetric;
import com.piggymetrics.statistics.domain.timeseries.StatisticMetric;
import com.piggymetrics.statistics.repository.DataPointRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class StatisticsServiceImpl implements StatisticsService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private DataPointRepository repository;
@Autowired
private ExchangeRatesService ratesService;
/**
* {@inheritDoc}
*/
@Override
public List<DataPoint> findByAccountName(String accountName) {
Assert.hasLength(accountName);
return repository.findByIdAccount(accountName);
}
/**
* {@inheritDoc}
*/
@Override
public DataPoint save(String accountName, Account account) {
Instant instant = LocalDate.now().atStartOfDay()
.atZone(ZoneId.systemDefault()).toInstant();
DataPointId pointId = new DataPointId(accountName, Date.from(instant));
Set<ItemMetric> incomes = account.getIncomes().stream()
.map(this::createItemMetric)
.collect(Collectors.toSet());
Set<ItemMetric> expenses = account.getExpenses().stream()
.map(this::createItemMetric)
.collect(Collectors.toSet());
Map<StatisticMetric, BigDecimal> statistics = createStatisticMetrics(incomes, expenses, account.getSaving());
DataPoint dataPoint = new DataPoint();
dataPoint.setId(pointId);
dataPoint.setIncomes(incomes);
dataPoint.setExpenses(expenses);
dataPoint.setStatistics(statistics);
dataPoint.setRates(ratesService.getCurrentRates());
log.debug("new datapoint has been created: {}", pointId);
return repository.save(dataPoint);
}
private Map<StatisticMetric, BigDecimal> createStatisticMetrics(Set<ItemMetric> incomes, Set<ItemMetric> expenses, Saving saving) {
BigDecimal savingAmount = ratesService.convert(saving.getCurrency(), Currency.getBase(), saving.getAmount());
BigDecimal expensesAmount = expenses.stream()
.map(ItemMetric::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal incomesAmount = incomes.stream()
.map(ItemMetric::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
return ImmutableMap.of(
StatisticMetric.EXPENSES_AMOUNT, expensesAmount,
StatisticMetric.INCOMES_AMOUNT, incomesAmount,
StatisticMetric.SAVING_AMOUNT, savingAmount
);
}
/**
* Normalizes given item amount to {@link Currency#getBase()} currency with
* {@link TimePeriod#getBase()} time period
*/
private ItemMetric createItemMetric(Item item) {
BigDecimal amount = ratesService
.convert(item.getCurrency(), Currency.getBase(), item.getAmount())
.divide(item.getPeriod().getBaseRatio(), 4, RoundingMode.HALF_UP);
return new ItemMetric(item.getTitle(), amount);
}
}
| 3,469 | 29.982143 | 132 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/main/java/com/piggymetrics/statistics/service/security/CustomUserInfoTokenServices.java
|
package com.piggymetrics.statistics.service.security;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
import org.springframework.boot.autoconfigure.security.oauth2.resource.FixedAuthoritiesExtractor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import java.util.*;
/**
* Extended implementation of {@link org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices}
*
* By default, it designed to return only user details. This class provides {@link #getRequest(Map)} method, which
* returns clientId and scope of calling service. This information used in controller's security checks.
*/
public class CustomUserInfoTokenServices implements ResourceServerTokenServices {
protected final Log logger = LogFactory.getLog(getClass());
private static final String[] PRINCIPAL_KEYS = new String[] { "user", "username",
"userid", "user_id", "login", "id", "name" };
private final String userInfoEndpointUrl;
private final String clientId;
private OAuth2RestOperations restTemplate;
private String tokenType = DefaultOAuth2AccessToken.BEARER_TYPE;
private AuthoritiesExtractor authoritiesExtractor = new FixedAuthoritiesExtractor();
public CustomUserInfoTokenServices(String userInfoEndpointUrl, String clientId) {
this.userInfoEndpointUrl = userInfoEndpointUrl;
this.clientId = clientId;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public void setRestTemplate(OAuth2RestOperations restTemplate) {
this.restTemplate = restTemplate;
}
public void setAuthoritiesExtractor(AuthoritiesExtractor authoritiesExtractor) {
this.authoritiesExtractor = authoritiesExtractor;
}
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
throws AuthenticationException, InvalidTokenException {
Map<String, Object> map = getMap(this.userInfoEndpointUrl, accessToken);
if (map.containsKey("error")) {
this.logger.debug("userinfo returned error: " + map.get("error"));
throw new InvalidTokenException(accessToken);
}
return extractAuthentication(map);
}
private OAuth2Authentication extractAuthentication(Map<String, Object> map) {
Object principal = getPrincipal(map);
OAuth2Request request = getRequest(map);
List<GrantedAuthority> authorities = this.authoritiesExtractor
.extractAuthorities(map);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
principal, "N/A", authorities);
token.setDetails(map);
return new OAuth2Authentication(request, token);
}
private Object getPrincipal(Map<String, Object> map) {
for (String key : PRINCIPAL_KEYS) {
if (map.containsKey(key)) {
return map.get(key);
}
}
return "unknown";
}
@SuppressWarnings({ "unchecked" })
private OAuth2Request getRequest(Map<String, Object> map) {
Map<String, Object> request = (Map<String, Object>) map.get("oauth2Request");
String clientId = (String) request.get("clientId");
Set<String> scope = new LinkedHashSet<>(request.containsKey("scope") ?
(Collection<String>) request.get("scope") : Collections.<String>emptySet());
return new OAuth2Request(null, clientId, null, true, new HashSet<>(scope),
null, null, null, null);
}
@Override
public OAuth2AccessToken readAccessToken(String accessToken) {
throw new UnsupportedOperationException("Not supported: read access token");
}
@SuppressWarnings({ "unchecked" })
private Map<String, Object> getMap(String path, String accessToken) {
this.logger.debug("Getting user info from: " + path);
try {
OAuth2RestOperations restTemplate = this.restTemplate;
if (restTemplate == null) {
BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails();
resource.setClientId(this.clientId);
restTemplate = new OAuth2RestTemplate(resource);
}
OAuth2AccessToken existingToken = restTemplate.getOAuth2ClientContext()
.getAccessToken();
if (existingToken == null || !accessToken.equals(existingToken.getValue())) {
DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(
accessToken);
token.setTokenType(this.tokenType);
restTemplate.getOAuth2ClientContext().setAccessToken(token);
}
return restTemplate.getForEntity(path, Map.class).getBody();
}
catch (Exception ex) {
this.logger.info("Could not fetch user details: " + ex.getClass() + ", "
+ ex.getMessage());
return Collections.<String, Object>singletonMap("error",
"Could not fetch user details");
}
}
}
| 5,497 | 38.553957 | 123 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/test/java/com/piggymetrics/statistics/StatisticsServiceApplicationTests.java
|
package com.piggymetrics.statistics;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class StatisticsServiceApplicationTests {
@Test
public void contextLoads() {
}
}
| 355 | 19.941176 | 60 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/test/java/com/piggymetrics/statistics/client/ExchangeRatesClientTest.java
|
package com.piggymetrics.statistics.client;
import com.piggymetrics.statistics.domain.Currency;
import com.piggymetrics.statistics.domain.ExchangeRatesContainer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.LocalDate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ExchangeRatesClientTest {
@Autowired
private ExchangeRatesClient client;
@Test
public void shouldRetrieveExchangeRates() {
ExchangeRatesContainer container = client.getRates(Currency.getBase());
assertEquals(container.getDate(), LocalDate.now());
assertEquals(container.getBase(), Currency.getBase());
assertNotNull(container.getRates());
assertNotNull(container.getRates().get(Currency.USD.name()));
assertNotNull(container.getRates().get(Currency.EUR.name()));
assertNotNull(container.getRates().get(Currency.RUB.name()));
}
@Test
public void shouldRetrieveExchangeRatesForSpecifiedCurrency() {
Currency requestedCurrency = Currency.EUR;
ExchangeRatesContainer container = client.getRates(Currency.getBase());
assertEquals(container.getDate(), LocalDate.now());
assertEquals(container.getBase(), Currency.getBase());
assertNotNull(container.getRates());
assertNotNull(container.getRates().get(requestedCurrency.name()));
}
}
| 1,553 | 30.714286 | 73 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/test/java/com/piggymetrics/statistics/controller/StatisticsControllerTest.java
|
package com.piggymetrics.statistics.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.piggymetrics.statistics.domain.Account;
import com.piggymetrics.statistics.domain.Currency;
import com.piggymetrics.statistics.domain.Item;
import com.piggymetrics.statistics.domain.Saving;
import com.piggymetrics.statistics.domain.TimePeriod;
import com.piggymetrics.statistics.domain.timeseries.DataPoint;
import com.piggymetrics.statistics.domain.timeseries.DataPointId;
import com.piggymetrics.statistics.service.StatisticsService;
import com.sun.security.auth.UserPrincipal;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.math.BigDecimal;
import java.util.Date;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
public class StatisticsControllerTest {
private static final ObjectMapper mapper = new ObjectMapper();
@InjectMocks
private StatisticsController statisticsController;
@Mock
private StatisticsService statisticsService;
private MockMvc mockMvc;
@Before
public void setup() {
initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(statisticsController).build();
}
@Test
public void shouldGetStatisticsByAccountName() throws Exception {
final DataPoint dataPoint = new DataPoint();
dataPoint.setId(new DataPointId("test", new Date()));
when(statisticsService.findByAccountName(dataPoint.getId().getAccount()))
.thenReturn(ImmutableList.of(dataPoint));
mockMvc.perform(get("/test").principal(new UserPrincipal(dataPoint.getId().getAccount())))
.andExpect(jsonPath("$[0].id.account").value(dataPoint.getId().getAccount()))
.andExpect(status().isOk());
}
@Test
public void shouldGetCurrentAccountStatistics() throws Exception {
final DataPoint dataPoint = new DataPoint();
dataPoint.setId(new DataPointId("test", new Date()));
when(statisticsService.findByAccountName(dataPoint.getId().getAccount()))
.thenReturn(ImmutableList.of(dataPoint));
mockMvc.perform(get("/current").principal(new UserPrincipal(dataPoint.getId().getAccount())))
.andExpect(jsonPath("$[0].id.account").value(dataPoint.getId().getAccount()))
.andExpect(status().isOk());
}
@Test
public void shouldSaveAccountStatistics() throws Exception {
Saving saving = new Saving();
saving.setAmount(new BigDecimal(1500));
saving.setCurrency(Currency.USD);
saving.setInterest(new BigDecimal("3.32"));
saving.setDeposit(true);
saving.setCapitalization(false);
Item grocery = new Item();
grocery.setTitle("Grocery");
grocery.setAmount(new BigDecimal(10));
grocery.setCurrency(Currency.USD);
grocery.setPeriod(TimePeriod.DAY);
Item salary = new Item();
salary.setTitle("Salary");
salary.setAmount(new BigDecimal(9100));
salary.setCurrency(Currency.USD);
salary.setPeriod(TimePeriod.MONTH);
final Account account = new Account();
account.setSaving(saving);
account.setExpenses(ImmutableList.of(grocery));
account.setIncomes(ImmutableList.of(salary));
String json = mapper.writeValueAsString(account);
mockMvc.perform(put("/test").contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isOk());
verify(statisticsService, times(1)).save(anyString(), any(Account.class));
}
}
| 4,317 | 34.68595 | 95 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/test/java/com/piggymetrics/statistics/repository/DataPointRepositoryTest.java
|
package com.piggymetrics.statistics.repository;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.piggymetrics.statistics.domain.timeseries.DataPoint;
import com.piggymetrics.statistics.domain.timeseries.DataPointId;
import com.piggymetrics.statistics.domain.timeseries.ItemMetric;
import com.piggymetrics.statistics.domain.timeseries.StatisticMetric;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@DataMongoTest
public class DataPointRepositoryTest {
@Autowired
private DataPointRepository repository;
@Test
public void shouldSaveDataPoint() {
ItemMetric salary = new ItemMetric("salary", new BigDecimal(20_000));
ItemMetric grocery = new ItemMetric("grocery", new BigDecimal(1_000));
ItemMetric vacation = new ItemMetric("vacation", new BigDecimal(2_000));
DataPointId pointId = new DataPointId("test-account", new Date(0));
DataPoint point = new DataPoint();
point.setId(pointId);
point.setIncomes(Sets.newHashSet(salary));
point.setExpenses(Sets.newHashSet(grocery, vacation));
point.setStatistics(ImmutableMap.of(
StatisticMetric.SAVING_AMOUNT, new BigDecimal(400_000),
StatisticMetric.INCOMES_AMOUNT, new BigDecimal(20_000),
StatisticMetric.EXPENSES_AMOUNT, new BigDecimal(3_000)
));
repository.save(point);
List<DataPoint> points = repository.findByIdAccount(pointId.getAccount());
assertEquals(1, points.size());
assertEquals(pointId.getDate(), points.get(0).getId().getDate());
assertEquals(point.getStatistics().size(), points.get(0).getStatistics().size());
assertEquals(point.getIncomes().size(), points.get(0).getIncomes().size());
assertEquals(point.getExpenses().size(), points.get(0).getExpenses().size());
}
@Test
public void shouldRewriteDataPointWithinADay() {
final BigDecimal earlyAmount = new BigDecimal(100);
final BigDecimal lateAmount = new BigDecimal(200);
DataPointId pointId = new DataPointId("test-account", new Date(0));
DataPoint earlier = new DataPoint();
earlier.setId(pointId);
earlier.setStatistics(ImmutableMap.of(
StatisticMetric.SAVING_AMOUNT, earlyAmount
));
repository.save(earlier);
DataPoint later = new DataPoint();
later.setId(pointId);
later.setStatistics(ImmutableMap.of(
StatisticMetric.SAVING_AMOUNT, lateAmount
));
repository.save(later);
List<DataPoint> points = repository.findByIdAccount(pointId.getAccount());
assertEquals(1, points.size());
assertEquals(lateAmount, points.get(0).getStatistics().get(StatisticMetric.SAVING_AMOUNT));
}
}
| 2,913 | 32.113636 | 93 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/test/java/com/piggymetrics/statistics/service/ExchangeRatesServiceImplTest.java
|
package com.piggymetrics.statistics.service;
import com.google.common.collect.ImmutableMap;
import com.piggymetrics.statistics.client.ExchangeRatesClient;
import com.piggymetrics.statistics.domain.Currency;
import com.piggymetrics.statistics.domain.ExchangeRatesContainer;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.math.BigDecimal;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
public class ExchangeRatesServiceImplTest {
@InjectMocks
private ExchangeRatesServiceImpl ratesService;
@Mock
private ExchangeRatesClient client;
@Before
public void setup() {
initMocks(this);
}
@Test
public void shouldReturnCurrentRatesWhenContainerIsEmptySoFar() {
ExchangeRatesContainer container = new ExchangeRatesContainer();
container.setRates(ImmutableMap.of(
Currency.EUR.name(), new BigDecimal("0.8"),
Currency.RUB.name(), new BigDecimal("80")
));
when(client.getRates(Currency.getBase())).thenReturn(container);
Map<Currency, BigDecimal> result = ratesService.getCurrentRates();
verify(client, times(1)).getRates(Currency.getBase());
assertEquals(container.getRates().get(Currency.EUR.name()), result.get(Currency.EUR));
assertEquals(container.getRates().get(Currency.RUB.name()), result.get(Currency.RUB));
assertEquals(BigDecimal.ONE, result.get(Currency.USD));
}
@Test
public void shouldNotRequestRatesWhenTodaysContainerAlreadyExists() {
ExchangeRatesContainer container = new ExchangeRatesContainer();
container.setRates(ImmutableMap.of(
Currency.EUR.name(), new BigDecimal("0.8"),
Currency.RUB.name(), new BigDecimal("80")
));
when(client.getRates(Currency.getBase())).thenReturn(container);
// initialize container
ratesService.getCurrentRates();
// use existing container
ratesService.getCurrentRates();
verify(client, times(1)).getRates(Currency.getBase());
}
@Test
public void shouldConvertCurrency() {
ExchangeRatesContainer container = new ExchangeRatesContainer();
container.setRates(ImmutableMap.of(
Currency.EUR.name(), new BigDecimal("0.8"),
Currency.RUB.name(), new BigDecimal("80")
));
when(client.getRates(Currency.getBase())).thenReturn(container);
final BigDecimal amount = new BigDecimal(100);
final BigDecimal expectedConvertionResult = new BigDecimal("1.25");
BigDecimal result = ratesService.convert(Currency.RUB, Currency.USD, amount);
assertTrue(expectedConvertionResult.compareTo(result) == 0);
}
@Test(expected = IllegalArgumentException.class)
public void shouldFailToConvertWhenAmountIsNull() {
ratesService.convert(Currency.EUR, Currency.RUB, null);
}
}
| 2,830 | 28.8 | 88 |
java
|
piggymetrics
|
piggymetrics-master/statistics-service/src/test/java/com/piggymetrics/statistics/service/StatisticsServiceImplTest.java
|
package com.piggymetrics.statistics.service;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.piggymetrics.statistics.domain.Account;
import com.piggymetrics.statistics.domain.Currency;
import com.piggymetrics.statistics.domain.Item;
import com.piggymetrics.statistics.domain.Saving;
import com.piggymetrics.statistics.domain.TimePeriod;
import com.piggymetrics.statistics.domain.timeseries.DataPoint;
import com.piggymetrics.statistics.domain.timeseries.ItemMetric;
import com.piggymetrics.statistics.domain.timeseries.StatisticMetric;
import com.piggymetrics.statistics.repository.DataPointRepository;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class StatisticsServiceImplTest {
@InjectMocks
private StatisticsServiceImpl statisticsService;
@Mock
private ExchangeRatesServiceImpl ratesService;
@Mock
private DataPointRepository repository;
@Before
public void setup() {
initMocks(this);
}
@Test
public void shouldFindDataPointListByAccountName() {
final List<DataPoint> list = ImmutableList.of(new DataPoint());
when(repository.findByIdAccount("test")).thenReturn(list);
List<DataPoint> result = statisticsService.findByAccountName("test");
assertEquals(list, result);
}
@Test(expected = IllegalArgumentException.class)
public void shouldFailToFindDataPointWhenAccountNameIsNull() {
statisticsService.findByAccountName(null);
}
@Test(expected = IllegalArgumentException.class)
public void shouldFailToFindDataPointWhenAccountNameIsEmpty() {
statisticsService.findByAccountName("");
}
@Test
public void shouldSaveDataPoint() {
/**
* Given
*/
Item salary = new Item();
salary.setTitle("Salary");
salary.setAmount(new BigDecimal(9100));
salary.setCurrency(Currency.USD);
salary.setPeriod(TimePeriod.MONTH);
Item grocery = new Item();
grocery.setTitle("Grocery");
grocery.setAmount(new BigDecimal(500));
grocery.setCurrency(Currency.RUB);
grocery.setPeriod(TimePeriod.DAY);
Item vacation = new Item();
vacation.setTitle("Vacation");
vacation.setAmount(new BigDecimal(3400));
vacation.setCurrency(Currency.EUR);
vacation.setPeriod(TimePeriod.YEAR);
Saving saving = new Saving();
saving.setAmount(new BigDecimal(1000));
saving.setCurrency(Currency.EUR);
saving.setInterest(new BigDecimal(3.2));
saving.setDeposit(true);
saving.setCapitalization(false);
Account account = new Account();
account.setIncomes(ImmutableList.of(salary));
account.setExpenses(ImmutableList.of(grocery, vacation));
account.setSaving(saving);
final Map<Currency, BigDecimal> rates = ImmutableMap.of(
Currency.EUR, new BigDecimal("0.8"),
Currency.RUB, new BigDecimal("80"),
Currency.USD, BigDecimal.ONE
);
/**
* When
*/
when(ratesService.convert(any(Currency.class),any(Currency.class),any(BigDecimal.class)))
.then(i -> ((BigDecimal)i.getArgument(2))
.divide(rates.get(i.getArgument(0)), 4, RoundingMode.HALF_UP));
when(ratesService.getCurrentRates()).thenReturn(rates);
when(repository.save(any(DataPoint.class))).then(returnsFirstArg());
DataPoint dataPoint = statisticsService.save("test", account);
/**
* Then
*/
final BigDecimal expectedExpensesAmount = new BigDecimal("17.8861");
final BigDecimal expectedIncomesAmount = new BigDecimal("298.9802");
final BigDecimal expectedSavingAmount = new BigDecimal("1250");
final BigDecimal expectedNormalizedSalaryAmount = new BigDecimal("298.9802");
final BigDecimal expectedNormalizedVacationAmount = new BigDecimal("11.6361");
final BigDecimal expectedNormalizedGroceryAmount = new BigDecimal("6.25");
assertEquals(dataPoint.getId().getAccount(), "test");
assertEquals(dataPoint.getId().getDate(), Date.from(LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
assertTrue(expectedExpensesAmount.compareTo(dataPoint.getStatistics().get(StatisticMetric.EXPENSES_AMOUNT)) == 0);
assertTrue(expectedIncomesAmount.compareTo(dataPoint.getStatistics().get(StatisticMetric.INCOMES_AMOUNT)) == 0);
assertTrue(expectedSavingAmount.compareTo(dataPoint.getStatistics().get(StatisticMetric.SAVING_AMOUNT)) == 0);
ItemMetric salaryItemMetric = dataPoint.getIncomes().stream()
.filter(i -> i.getTitle().equals(salary.getTitle()))
.findFirst().get();
ItemMetric vacationItemMetric = dataPoint.getExpenses().stream()
.filter(i -> i.getTitle().equals(vacation.getTitle()))
.findFirst().get();
ItemMetric groceryItemMetric = dataPoint.getExpenses().stream()
.filter(i -> i.getTitle().equals(grocery.getTitle()))
.findFirst().get();
assertTrue(expectedNormalizedSalaryAmount.compareTo(salaryItemMetric.getAmount()) == 0);
assertTrue(expectedNormalizedVacationAmount.compareTo(vacationItemMetric.getAmount()) == 0);
assertTrue(expectedNormalizedGroceryAmount.compareTo(groceryItemMetric.getAmount()) == 0);
assertEquals(rates, dataPoint.getRates());
verify(repository, times(1)).save(dataPoint);
}
}
| 5,636 | 32.754491 | 130 |
java
|
piggymetrics
|
piggymetrics-master/turbine-stream-service/src/main/java/com/piggymetrics/turbine/TurbineStreamServiceApplication.java
|
package com.piggymetrics.turbine;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.turbine.stream.EnableTurbineStream;
@SpringBootApplication
@EnableTurbineStream
@EnableDiscoveryClient
public class TurbineStreamServiceApplication {
public static void main(String[] args) {
SpringApplication.run(TurbineStreamServiceApplication.class, args);
}
}
| 538 | 30.705882 | 76 |
java
|
piggymetrics
|
piggymetrics-master/turbine-stream-service/src/test/java/com/piggymetrics/turbine/TurbineStreamServiceApplicationTests.java
|
package com.piggymetrics.turbine;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TurbineStreamServiceApplicationTests {
@Test
public void contextLoads() {
}
}
| 355 | 19.941176 | 60 |
java
|
gnucash-android
|
gnucash-android-master/app/src/androidTest/java/org/gnucash/android/test/ui/AccountsActivityTest.java
|
/*
* Copyright (c) 2012 - 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.test.ui;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.preference.PreferenceManager;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.ActivityTestRule;
import android.support.test.rule.GrantPermissionRule;
import android.support.test.runner.AndroidJUnit4;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import com.kobakei.ratethisapp.RateThisApp;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseHelper;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.Split;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.receivers.AccountCreator;
import org.gnucash.android.test.ui.util.DisableAnimationsRule;
import org.gnucash.android.ui.account.AccountsActivity;
import org.gnucash.android.ui.account.AccountsListFragment;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.math.BigDecimal;
import java.util.List;
import static android.support.test.espresso.Espresso.onData;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu;
import static android.support.test.espresso.action.ViewActions.clearText;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.scrollTo;
import static android.support.test.espresso.action.ViewActions.swipeRight;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant;
import static android.support.test.espresso.matcher.ViewMatchers.isChecked;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.isEnabled;
import static android.support.test.espresso.matcher.ViewMatchers.isNotChecked;
import static android.support.test.espresso.matcher.ViewMatchers.withEffectiveVisibility;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
@RunWith(AndroidJUnit4.class)
public class AccountsActivityTest {
private static final String ACCOUNTS_CURRENCY_CODE = "USD";
// Don't add static here, otherwise it gets set to null by super.tearDown()
private final Commodity ACCOUNTS_CURRENCY = Commodity.getInstance(ACCOUNTS_CURRENCY_CODE);
private static final String SIMPLE_ACCOUNT_NAME = "Simple account";
private static final String SIMPLE_ACCOUNT_UID = "simple-account";
private static final String ROOT_ACCOUNT_NAME = "Root account";
private static final String ROOT_ACCOUNT_UID = "root-account";
private static final String PARENT_ACCOUNT_NAME = "Parent account";
private static final String PARENT_ACCOUNT_UID = "parent-account";
private static final String CHILD_ACCOUNT_UID = "child-account";
private static final String CHILD_ACCOUNT_NAME = "Child account";
public static final String TEST_DB_NAME = "test_gnucash_db.sqlite";
private static DatabaseHelper mDbHelper;
private static SQLiteDatabase mDb;
private static AccountsDbAdapter mAccountsDbAdapter;
private static TransactionsDbAdapter mTransactionsDbAdapter;
private static SplitsDbAdapter mSplitsDbAdapter;
private AccountsActivity mAccountsActivity;
public AccountsActivityTest() {
// super(AccountsActivity.class);
}
@Rule public GrantPermissionRule animationPermissionsRule = GrantPermissionRule.grant(Manifest.permission.SET_ANIMATION_SCALE);
@ClassRule public static DisableAnimationsRule disableAnimationsRule = new DisableAnimationsRule();
@Rule
public ActivityTestRule<AccountsActivity> mActivityRule = new ActivityTestRule<>(AccountsActivity.class);
@BeforeClass
public static void prepTest(){
preventFirstRunDialogs(GnuCashApplication.getAppContext());
String activeBookUID = BooksDbAdapter.getInstance().getActiveBookUID();
mDbHelper = new DatabaseHelper(GnuCashApplication.getAppContext(), activeBookUID);
try {
mDb = mDbHelper.getWritableDatabase();
} catch (SQLException e) {
Log.e("AccountsActivityTest", "Error getting database: " + e.getMessage());
mDb = mDbHelper.getReadableDatabase();
}
mSplitsDbAdapter = SplitsDbAdapter.getInstance();
mTransactionsDbAdapter = TransactionsDbAdapter.getInstance();
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
CommoditiesDbAdapter commoditiesDbAdapter = new CommoditiesDbAdapter(mDb); //initialize commodity constants
}
@Before
public void setUp() throws Exception {
mAccountsActivity = mActivityRule.getActivity();
// testPreconditions();
mAccountsDbAdapter.deleteAllRecords(); //clear the data
Account simpleAccount = new Account(SIMPLE_ACCOUNT_NAME);
simpleAccount.setUID(SIMPLE_ACCOUNT_UID);
simpleAccount.setCommodity(Commodity.getInstance(ACCOUNTS_CURRENCY_CODE));
mAccountsDbAdapter.addRecord(simpleAccount, DatabaseAdapter.UpdateMethod.insert);
refreshAccountsList();
}
/**
* Prevents the first-run dialogs (Whats new, Create accounts etc) from being displayed when testing
* @param context Application context
*/
public static void preventFirstRunDialogs(Context context) {
AccountsActivity.rateAppConfig = new RateThisApp.Config(10000, 10000);
Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
//do not show first run dialog
editor.putBoolean(context.getString(R.string.key_first_run), false);
editor.putInt(AccountsActivity.LAST_OPEN_TAB_INDEX, AccountsActivity.INDEX_TOP_LEVEL_ACCOUNTS_FRAGMENT);
//do not show "What's new" dialog
String minorVersion = context.getString(R.string.app_minor_version);
int currentMinor = Integer.parseInt(minorVersion);
editor.putInt(context.getString(R.string.key_previous_minor_version), currentMinor);
editor.commit();
}
public void testDisplayAccountsList(){
AccountsActivity.createDefaultAccounts("EUR", mAccountsActivity);
mAccountsActivity.recreate();
refreshAccountsList();
sleep(1000);
onView(withText("Assets")).perform(scrollTo());
onView(withText("Expenses")).perform(click());
onView(withText("Books")).perform(scrollTo());
}
@Test
public void testSearchAccounts(){
String SEARCH_ACCOUNT_NAME = "Search Account";
Account account = new Account(SEARCH_ACCOUNT_NAME);
account.setParentUID(SIMPLE_ACCOUNT_UID);
mAccountsDbAdapter.addRecord(account, DatabaseAdapter.UpdateMethod.insert);
//enter search query
// ActionBarUtils.clickSherlockActionBarItem(mSolo, R.id.menu_search);
onView(withId(R.id.menu_search)).perform(click());
onView(withId(R.id.search_src_text)).perform(typeText("Se"));
onView(withText(SEARCH_ACCOUNT_NAME)).check(matches(isDisplayed()));
onView(withId(R.id.search_src_text)).perform(clearText());
onView(withText(SEARCH_ACCOUNT_NAME)).check(doesNotExist());
}
/**
* Tests that an account can be created successfully and that the account list is sorted alphabetically.
*/
@Test
public void testCreateAccount(){
assertThat(mAccountsDbAdapter.getAllRecords()).hasSize(1);
onView(allOf(isDisplayed(), withId(R.id.fab_create_account))).perform(click());
String NEW_ACCOUNT_NAME = "A New Account";
onView(withId(R.id.input_account_name)).perform(typeText(NEW_ACCOUNT_NAME), closeSoftKeyboard());
sleep(1000);
onView(withId(R.id.checkbox_placeholder_account))
.check(matches(isNotChecked()))
.perform(click());
onView(withId(R.id.menu_save)).perform(click());
List<Account> accounts = mAccountsDbAdapter.getAllRecords();
assertThat(accounts).isNotNull();
assertThat(accounts).hasSize(2);
Account newestAccount = accounts.get(0); //because of alphabetical sorting
assertThat(newestAccount.getName()).isEqualTo(NEW_ACCOUNT_NAME);
assertThat(newestAccount.getCommodity().getCurrencyCode()).isEqualTo(Money.DEFAULT_CURRENCY_CODE);
assertThat(newestAccount.isPlaceholderAccount()).isTrue();
}
@Test
public void should_IncludeFutureTransactionsInAccountBalance(){
Transaction transaction = new Transaction("Future transaction");
Split split1 = new Split(new Money("4.15", ACCOUNTS_CURRENCY_CODE), SIMPLE_ACCOUNT_UID);
transaction.addSplit(split1);
transaction.setTime(System.currentTimeMillis() + 4815162342L);
mTransactionsDbAdapter.addRecord(transaction);
refreshAccountsList();
List<Transaction> trxns = mTransactionsDbAdapter.getAllTransactions();
onView(first(withText(containsString("4.15")))).check(matches(isDisplayed()));
}
@Test
public void testChangeParentAccount() {
final String accountName = "Euro Account";
Account account = new Account(accountName, Commodity.EUR);
mAccountsDbAdapter.addRecord(account, DatabaseAdapter.UpdateMethod.insert);
refreshAccountsList();
onView(withText(accountName)).perform(click());
openActionBarOverflowOrOptionsMenu(mAccountsActivity);
onView(withText(R.string.title_edit_account)).perform(click());
onView(withId(R.id.fragment_account_form)).check(matches(isDisplayed()));
Espresso.closeSoftKeyboard();
onView(withId(R.id.checkbox_parent_account)).perform(scrollTo())
.check(matches(isNotChecked()))
.perform(click());
// FIXME: explicitly select the parent account
onView(withId(R.id.input_parent_account)).check(matches(isEnabled())).perform(click());
onView(withText(SIMPLE_ACCOUNT_NAME)).perform(click());
onView(withId(R.id.menu_save)).perform(click());
Account editedAccount = mAccountsDbAdapter.getRecord(account.getUID());
String parentUID = editedAccount.getParentUID();
assertThat(parentUID).isNotNull();
assertThat(parentUID).isEqualTo(SIMPLE_ACCOUNT_UID);
}
/**
* When creating a sub-account (starting from within another account), if we change the account
* type to another type with no accounts of that type, then the parent account list should be hidden.
* The account which is then created is not a sub-account, but rather a top-level account
*/
@Test
public void shouldHideParentAccountViewWhenNoParentsExist(){
onView(allOf(withText(SIMPLE_ACCOUNT_NAME), isDisplayed())).perform(click());
onView(withId(R.id.fragment_transaction_list)).perform(swipeRight());
onView(withId(R.id.fab_create_transaction)).check(matches(isDisplayed())).perform(click());
sleep(1000);
onView(withId(R.id.checkbox_parent_account)).check(matches(allOf(isChecked())));
onView(withId(R.id.input_account_name)).perform(typeText("Trading account"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.layout_parent_account)).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
onView(withId(R.id.input_account_type_spinner)).perform(click());
onData(allOf(is(instanceOf(String.class)), is(AccountType.TRADING.name()))).perform(click());
onView(withId(R.id.layout_parent_account)).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.GONE)));
onView(withId(R.id.layout_parent_account)).check(matches(not(isDisplayed())));
onView(withId(R.id.menu_save)).perform(click());
sleep(1000);
//no sub-accounts
assertThat(mAccountsDbAdapter.getSubAccountCount(SIMPLE_ACCOUNT_UID)).isEqualTo(0);
assertThat(mAccountsDbAdapter.getSubAccountCount(mAccountsDbAdapter.getOrCreateGnuCashRootAccountUID())).isEqualTo(2);
assertThat(mAccountsDbAdapter.getSimpleAccountList()).extracting("mAccountType").contains(AccountType.TRADING);
}
@Test
public void testEditAccount(){
refreshAccountsList();
onView(allOf(withParent(hasDescendant(withText(SIMPLE_ACCOUNT_NAME))),
withId(R.id.options_menu))).perform(click());
// onView(withId(R.id.options_menu)).perform(click()); //there should only be one account visible
sleep(1000);
onView(withText(R.string.title_edit_account)).check(matches(isDisplayed())).perform(click());
// onView(withId(R.id.context_menu_edit_accounts)).check(matches(isDisplayed())).perform(click());
onView(withId(R.id.fragment_account_form)).check(matches(isDisplayed()));
String editedAccountName = "An Edited Account";
onView(withId(R.id.input_account_name)).perform(clearText()).perform(typeText(editedAccountName));
onView(withId(R.id.menu_save)).perform(click());
List<Account> accounts = mAccountsDbAdapter.getAllRecords();
Account latest = accounts.get(0); //will be the first due to alphabetical sorting
assertThat(latest.getName()).isEqualTo(editedAccountName);
assertThat(latest.getCommodity().getCurrencyCode()).isEqualTo(ACCOUNTS_CURRENCY_CODE);
}
@Test
public void editingAccountShouldNotDeleteTransactions(){
onView(allOf(withParent(hasDescendant(withText(SIMPLE_ACCOUNT_NAME))),
withId(R.id.options_menu),
isDisplayed())).perform(click());
Account account = new Account("Transfer Account");
account.setCommodity(Commodity.getInstance(ACCOUNTS_CURRENCY.getCurrencyCode()));
Transaction transaction = new Transaction("Simple transaction");
transaction.setCommodity(ACCOUNTS_CURRENCY);
Split split = new Split(new Money(BigDecimal.TEN, ACCOUNTS_CURRENCY), account.getUID());
transaction.addSplit(split);
transaction.addSplit(split.createPair(SIMPLE_ACCOUNT_UID));
account.addTransaction(transaction);
mAccountsDbAdapter.addRecord(account, DatabaseAdapter.UpdateMethod.insert);
assertThat(mAccountsDbAdapter.getRecord(SIMPLE_ACCOUNT_UID).getTransactionCount()).isEqualTo(1);
assertThat(mSplitsDbAdapter.getSplitsForTransaction(transaction.getUID())).hasSize(2);
onView(withText(R.string.title_edit_account)).perform(click());
onView(withId(R.id.menu_save)).perform(click());
assertThat(mAccountsDbAdapter.getRecord(SIMPLE_ACCOUNT_UID).getTransactionCount()).isEqualTo(1);
assertThat(mSplitsDbAdapter.fetchSplitsForAccount(SIMPLE_ACCOUNT_UID).getCount()).isEqualTo(1);
assertThat(mSplitsDbAdapter.getSplitsForTransaction(transaction.getUID())).hasSize(2);
}
/**
* Sleep the thread for a specified period
* @param millis Duration to sleep in milliseconds
*/
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void testDeleteSimpleAccount() {
refreshAccountsList();
assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(2);
onView(allOf(withParent(hasDescendant(withText(SIMPLE_ACCOUNT_NAME))),
withId(R.id.options_menu))).perform(click());
onView(withText(R.string.menu_delete)).perform(click());
assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(1);
List<Account> accounts = mAccountsDbAdapter.getAllRecords();
assertThat(accounts).hasSize(0); //root account is never returned
}
@Test
public void testDeleteAccountWithSubaccounts() {
refreshAccountsList();
Account account = new Account("Sub-account");
account.setParentUID(SIMPLE_ACCOUNT_UID);
account.setUID(CHILD_ACCOUNT_UID);
mAccountsDbAdapter.addRecord(account);
refreshAccountsList();
onView(allOf(withParent(hasDescendant(withText(SIMPLE_ACCOUNT_NAME))),
withId(R.id.options_menu))).perform(click());
onView(withText(R.string.menu_delete)).perform(click());
onView(allOf(withParent(withId(R.id.accounts_options)),
withId(R.id.radio_delete))).perform(click());
onView(withText(R.string.alert_dialog_ok_delete)).perform(click());
assertThat(accountExists(SIMPLE_ACCOUNT_UID)).isFalse();
assertThat(accountExists(CHILD_ACCOUNT_UID)).isFalse();
}
@Test
public void testDeleteAccountMovingSubaccounts() {
long accountCount = mAccountsDbAdapter.getRecordsCount();
Account subAccount = new Account("Child account");
subAccount.setParentUID(SIMPLE_ACCOUNT_UID);
Account tranferAcct = new Account("Other account");
mAccountsDbAdapter.addRecord(subAccount, DatabaseAdapter.UpdateMethod.insert);
mAccountsDbAdapter.addRecord(tranferAcct, DatabaseAdapter.UpdateMethod.insert);
assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(accountCount+2);
refreshAccountsList();
onView(allOf(withParent(hasDescendant(withText(SIMPLE_ACCOUNT_NAME))),
withId(R.id.options_menu))).perform(click());
onView(withText(R.string.menu_delete)).perform(click());
//// FIXME: 17.08.2016 This enabled check fails during some test runs - not reliable, investigate why
onView(allOf(withParent(withId(R.id.accounts_options)),
withId(R.id.radio_move))).check(matches(isEnabled())).perform(click());
onView(withText(R.string.alert_dialog_ok_delete)).perform(click());
assertThat(accountExists(SIMPLE_ACCOUNT_UID)).isFalse();
assertThat(accountExists(subAccount.getUID())).isTrue();
String newParentUID = mAccountsDbAdapter.getParentAccountUID(subAccount.getUID());
assertThat(newParentUID).isEqualTo(tranferAcct.getUID());
}
/**
* Checks if an account exists in the database
* @param accountUID GUID of the account
* @return {@code true} if the account exists, {@code false} otherwise
*/
private boolean accountExists(String accountUID) {
try {
mAccountsDbAdapter.getID(accountUID);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
//TODO: Test import of account file
//TODO: test settings activity
@Test
public void testIntentAccountCreation(){
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.putExtra(Intent.EXTRA_TITLE, "Intent Account");
intent.putExtra(Intent.EXTRA_UID, "intent-account");
intent.putExtra(Account.EXTRA_CURRENCY_CODE, "EUR");
intent.setType(Account.MIME_TYPE);
new AccountCreator().onReceive(mAccountsActivity, intent);
Account account = mAccountsDbAdapter.getRecord("intent-account");
assertThat(account).isNotNull();
assertThat(account.getName()).isEqualTo("Intent Account");
assertThat(account.getUID()).isEqualTo("intent-account");
assertThat(account.getCommodity().getCurrencyCode()).isEqualTo("EUR");
}
/**
* Tests that the setup wizard is displayed on first run
*/
@Test
public void shouldShowWizardOnFirstRun() throws Throwable {
Editor editor = PreferenceManager.getDefaultSharedPreferences(mAccountsActivity)
.edit();
//commit for immediate effect
editor.remove(mAccountsActivity.getString(R.string.key_first_run)).commit();
mActivityRule.runOnUiThread(new Runnable() {
@Override
public void run() {
mAccountsActivity.recreate();
}
});
//check that wizard is shown
onView(withText(mAccountsActivity.getString(R.string.title_setup_gnucash)))
.check(matches(isDisplayed()));
editor.putBoolean(mAccountsActivity.getString(R.string.key_first_run), false).apply();
}
@After
public void tearDown() throws Exception {
if (mAccountsActivity != null) {
mAccountsActivity.finish();
}
}
/**
* Refresh the account list fragment
*/
private void refreshAccountsList(){
try {
mActivityRule.runOnUiThread(new Runnable() {
@Override
public void run() {
Fragment fragment = mAccountsActivity.getCurrentAccountListFragment();
((AccountsListFragment) fragment).refresh();
}
});
} catch (Throwable throwable) {
System.err.println("Failed to refresh fragment");
}
}
/**
* Matcher to select the first of multiple views which are matched in the UI
* @param expected Matcher which fits multiple views
* @return Single match
*/
public static Matcher<View> first(final Matcher<View> expected){
return new TypeSafeMatcher<View>() {
private boolean first = false;
@Override
protected boolean matchesSafely(View item) {
if( expected.matches(item) && !first ){
return first = true;
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("Matcher.first( " + expected.toString() + " )" );
}
};
}
}
| 23,992 | 41.844643 | 131 |
java
|
gnucash-android
|
gnucash-android-master/app/src/androidTest/java/org/gnucash/android/test/ui/CalculatorEditTextTest.java
|
/*
* Copyright (c) 2012 - 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.test.ui;
import android.Manifest;
import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.support.test.rule.ActivityTestRule;
import android.support.test.rule.GrantPermissionRule;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseHelper;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.test.ui.util.DisableAnimationsRule;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.ui.transaction.TransactionsActivity;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.Espresso.pressBack;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static org.hamcrest.Matchers.not;
// TODO: Find out how to press the keys in the KeyboardView.
@RunWith(AndroidJUnit4.class)
public class CalculatorEditTextTest {
private static final String DUMMY_ACCOUNT_UID = "transactions-account";
private static final String DUMMY_ACCOUNT_NAME = "Transactions Account";
private static final String TRANSFER_ACCOUNT_NAME = "Transfer account";
private static final String TRANSFER_ACCOUNT_UID = "transfer_account";
public static final String CURRENCY_CODE = "USD";
private static DatabaseHelper mDbHelper;
private static AccountsDbAdapter mAccountsDbAdapter;
private static TransactionsDbAdapter mTransactionsDbAdapter;
private static SplitsDbAdapter mSplitsDbAdapter;
private TransactionsActivity mTransactionsActivity;
public CalculatorEditTextTest() {
}
@Rule public GrantPermissionRule animationPermissionsRule = GrantPermissionRule.grant(Manifest.permission.SET_ANIMATION_SCALE);
@ClassRule
public static DisableAnimationsRule disableAnimationsRule = new DisableAnimationsRule();
@Rule
public ActivityTestRule<TransactionsActivity> mActivityRule =
new ActivityTestRule<>(TransactionsActivity.class, true, false);
@BeforeClass
public static void prepTestCase(){
String activeBookUID = BooksDbAdapter.getInstance().getActiveBookUID();
mDbHelper = new DatabaseHelper(GnuCashApplication.getAppContext(), activeBookUID);
SQLiteDatabase mDb;
try {
mDb = mDbHelper.getWritableDatabase();
} catch (SQLException e) {
Log.e("CalculatorEditTextTest", "Error getting database: " + e.getMessage());
mDb = mDbHelper.getReadableDatabase();
}
// mSplitsDbAdapter = new SplitsDbAdapter(mDb);
// mTransactionsDbAdapter = new TransactionsDbAdapter(mDb, mSplitsDbAdapter);
// mAccountsDbAdapter = new AccountsDbAdapter(mDb, mTransactionsDbAdapter);
mSplitsDbAdapter = SplitsDbAdapter.getInstance();
mTransactionsDbAdapter = TransactionsDbAdapter.getInstance();
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
AccountsActivityTest.preventFirstRunDialogs(GnuCashApplication.getAppContext());
}
@Before
public void setUp() throws Exception {
mAccountsDbAdapter.deleteAllRecords();
CommoditiesDbAdapter commoditiesDbAdapter = CommoditiesDbAdapter.getInstance();
Commodity commodity = commoditiesDbAdapter.getCommodity(CURRENCY_CODE);
Account account = new Account(DUMMY_ACCOUNT_NAME, commodity);
account.setUID(DUMMY_ACCOUNT_UID);
Account account2 = new Account(TRANSFER_ACCOUNT_NAME, commodity);
account2.setUID(TRANSFER_ACCOUNT_UID);
mAccountsDbAdapter.addRecord(account);
mAccountsDbAdapter.addRecord(account2);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, DUMMY_ACCOUNT_UID);
mActivityRule.launchActivity(intent);
mTransactionsActivity = mActivityRule.getActivity();
}
/**
* Checks the calculator keyboard is showed/hided as expected.
*/
@Test
public void testShowingHidingOfCalculatorKeyboard() {
clickOnView(R.id.fab_create_transaction);
// Giving the focus to the amount field shows the keyboard
onView(withId(R.id.input_transaction_amount)).perform(click());
onView(withId(R.id.calculator_keyboard)).check(matches(isDisplayed()));
// Pressing back hides the keyboard (still with focus)
pressBack();
onView(withId(R.id.calculator_keyboard)).check(matches(not(isDisplayed())));
// Clicking the amount field already focused shows the keyboard again
clickOnView(R.id.input_transaction_amount);
onView(withId(R.id.calculator_keyboard)).check(matches(isDisplayed()));
// Changing the focus to another field hides the keyboard
clickOnView(R.id.input_transaction_name);
onView(withId(R.id.calculator_keyboard)).check(matches(not(isDisplayed())));
}
/**
* Simple wrapper for clicking on views with espresso
* @param viewId View resource ID
*/
private void clickOnView(int viewId){
onView(withId(viewId)).perform(click());
}
@After
public void tearDown() throws Exception {
if (mTransactionsActivity != null)
mTransactionsActivity.finish();
}
@AfterClass
public static void cleanup(){
if (mDbHelper != null)
mDbHelper.close();
}
}
| 6,872 | 37.396648 | 131 |
java
|
gnucash-android
|
gnucash-android-master/app/src/androidTest/java/org/gnucash/android/test/ui/ExportTransactionsTest.java
|
/*
* Copyright (c) 2012 - 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.test.ui;
import android.Manifest;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.support.test.InstrumentationRegistry;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.contrib.DrawerActions;
import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.GrantPermissionRule;
import android.support.test.runner.AndroidJUnit4;
import android.support.v7.preference.PreferenceManager;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import android.widget.CompoundButton;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseHelper;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.db.adapter.ScheduledActionDbAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.export.ExportFormat;
import org.gnucash.android.export.Exporter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.PeriodType;
import org.gnucash.android.model.ScheduledAction;
import org.gnucash.android.model.Split;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.ui.account.AccountsActivity;
import org.gnucash.android.ui.settings.PreferenceActivity;
import org.gnucash.android.util.BookUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import java.io.File;
import java.util.List;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.swipeUp;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.isEnabled;
import static android.support.test.espresso.matcher.ViewMatchers.withEffectiveVisibility;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ExportTransactionsTest extends
ActivityInstrumentationTestCase2<AccountsActivity> {
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private AccountsDbAdapter mAccountsDbAdapter;
private TransactionsDbAdapter mTransactionsDbAdapter;
private SplitsDbAdapter mSplitsDbAdapter;
private AccountsActivity mAcccountsActivity;
@Rule public GrantPermissionRule animationPermissionsRule = GrantPermissionRule.grant(Manifest.permission.SET_ANIMATION_SCALE);
public ExportTransactionsTest() {
super(AccountsActivity.class);
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
AccountsActivityTest.preventFirstRunDialogs(getInstrumentation().getTargetContext());
mAcccountsActivity = getActivity();
String activeBookUID = BooksDbAdapter.getInstance().getActiveBookUID();
mDbHelper = new DatabaseHelper(getActivity(), activeBookUID);
try {
mDb = mDbHelper.getWritableDatabase();
} catch (SQLException e) {
Log.e(getClass().getName(), "Error getting database: " + e.getMessage());
mDb = mDbHelper.getReadableDatabase();
}
mSplitsDbAdapter = SplitsDbAdapter.getInstance();
mTransactionsDbAdapter = TransactionsDbAdapter.getInstance();
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
//this call initializes the static variables like DEFAULT_COMMODITY which are used implicitly by accounts/transactions
@SuppressWarnings("unused")
CommoditiesDbAdapter commoditiesDbAdapter = new CommoditiesDbAdapter(mDb);
String currencyCode = GnuCashApplication.getDefaultCurrencyCode();
Commodity.DEFAULT_COMMODITY = CommoditiesDbAdapter.getInstance().getCommodity(currencyCode);
mAccountsDbAdapter.deleteAllRecords();
Account account = new Account("Exportable");
Transaction transaction = new Transaction("Pizza");
transaction.setNote("What up?");
transaction.setTime(System.currentTimeMillis());
Split split = new Split(new Money("8.99", currencyCode), account.getUID());
split.setMemo("Hawaii is the best!");
transaction.addSplit(split);
transaction.addSplit(split.createPair(
mAccountsDbAdapter.getOrCreateImbalanceAccountUID(Commodity.DEFAULT_COMMODITY)));
account.addTransaction(transaction);
mAccountsDbAdapter.addRecord(account, DatabaseAdapter.UpdateMethod.insert);
}
@Test
public void testCreateBackup(){
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(swipeUp());
onView(withText(R.string.title_settings)).perform(click());
onView(withText(R.string.header_backup_and_export_settings)).perform(click());
onView(withText(R.string.title_create_backup_pref)).perform(click());
assertToastDisplayed(R.string.toast_backup_successful);
}
/**
* Checks that a specific toast message is displayed
* @param toastString String that should be displayed
*/
private void assertToastDisplayed(int toastString) {
onView(withText(toastString))
.inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView()))))
.check(matches(isDisplayed()));
}
//todo: add testing of export flag to unit test
//todo: add test of ignore exported transactions to unit tests
@Override
@After public void tearDown() throws Exception {
mDbHelper.close();
mDb.close();
super.tearDown();
}
}
| 7,328 | 39.716667 | 128 |
java
|
gnucash-android
|
gnucash-android-master/app/src/androidTest/java/org/gnucash/android/test/ui/FirstRunWizardActivityTest.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.test.ui;
import android.Manifest;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.GrantPermissionRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseHelper;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.model.BaseModel;
import org.gnucash.android.ui.wizard.FirstRunWizardActivity;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests the first run wizard
* @author Ngewi Fet
*/
@RunWith(AndroidJUnit4.class)
public class FirstRunWizardActivityTest extends ActivityInstrumentationTestCase2<FirstRunWizardActivity>{
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private AccountsDbAdapter mAccountsDbAdapter;
private TransactionsDbAdapter mTransactionsDbAdapter;
private SplitsDbAdapter mSplitsDbAdapter;
FirstRunWizardActivity mActivity;
@Rule public GrantPermissionRule animationPermissionsRule = GrantPermissionRule.grant(Manifest.permission.SET_ANIMATION_SCALE);
public FirstRunWizardActivityTest() {
super(FirstRunWizardActivity.class);
}
@Before
public void setUp() throws Exception {
super.setUp();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
mActivity = getActivity();
mDbHelper = new DatabaseHelper(mActivity, BaseModel.generateUID());
try {
mDb = mDbHelper.getWritableDatabase();
} catch (SQLException e) {
Log.e(getClass().getName(), "Error getting database: " + e.getMessage());
mDb = mDbHelper.getReadableDatabase();
}
mSplitsDbAdapter = new SplitsDbAdapter(mDb);
mTransactionsDbAdapter = new TransactionsDbAdapter(mDb, mSplitsDbAdapter);
mAccountsDbAdapter = new AccountsDbAdapter(mDb, mTransactionsDbAdapter);
mAccountsDbAdapter.deleteAllRecords();
}
@Test
public void shouldRunWizardToEnd(){
assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(0);
onView(withId(R.id.btn_save)).perform(click());
onView(withText("EUR")).perform(click());
onView(withText(R.string.btn_wizard_next)).perform(click());
onView(withText(R.string.wizard_title_account_setup)).check(matches(isDisplayed()));
onView(withText(R.string.wizard_option_create_default_accounts)).perform(click());
onView(withText(R.string.btn_wizard_next)).perform(click());
onView(withText(R.string.wizard_option_auto_send_crash_reports)).perform(click());
onView(withText(R.string.btn_wizard_next)).perform(click());
onView(withText(R.string.review)).check(matches(isDisplayed()));
onView(withId(R.id.btn_save)).perform(click());
//default accounts should be created
long actualCount = GnuCashApplication.getAccountsDbAdapter().getRecordsCount();
assertThat(actualCount).isGreaterThan(60L);
boolean enableCrashlytics = GnuCashApplication.isCrashlyticsEnabled();
assertThat(enableCrashlytics).isTrue();
String defaultCurrencyCode = GnuCashApplication.getDefaultCurrencyCode();
assertThat(defaultCurrencyCode).isEqualTo("EUR");
}
@Test
public void shouldDisplayFullCurrencyList(){
assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(0);
onView(withId(R.id.btn_save)).perform(click());
onView(withText(R.string.wizard_option_currency_other)).perform(click());
onView(withText(R.string.btn_wizard_next)).perform(click());
onView(withText(R.string.wizard_title_select_currency)).check(matches(isDisplayed()));
// onData(allOf(is(instanceOf(String.class)), is("CHF")))
// .inAdapterView(withTagValue(is((Object)"currency_list_view"))).perform(click());
onView(withText("AFA - Afghani")).perform(click());
onView(withId(R.id.btn_save)).perform(click());
onView(withText(R.string.wizard_option_let_me_handle_it)).perform(click());
onView(withText(R.string.btn_wizard_next)).perform(click());
onView(withText(R.string.wizard_option_disable_crash_reports)).perform(click());
onView(withText(R.string.btn_wizard_next)).perform(click());
onView(withText(R.string.review)).check(matches(isDisplayed()));
onView(withId(R.id.btn_save)).perform(click());
//default accounts should not be created
assertThat(mAccountsDbAdapter.getRecordsCount()).isZero();
boolean enableCrashlytics = GnuCashApplication.isCrashlyticsEnabled();
assertThat(enableCrashlytics).isFalse();
String defaultCurrencyCode = GnuCashApplication.getDefaultCurrencyCode();
assertThat(defaultCurrencyCode).isEqualTo("AFA");
}
}
| 6,337 | 40.155844 | 131 |
java
|
gnucash-android
|
gnucash-android-master/app/src/androidTest/java/org/gnucash/android/test/ui/MultiBookTest.java
|
/*
* Copyright (c) 2016 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.test.ui;
import android.Manifest;
import android.support.test.espresso.contrib.DrawerActions;
import android.support.test.espresso.intent.Intents;
import android.support.test.espresso.intent.rule.IntentsTestRule;
import android.support.test.rule.GrantPermissionRule;
import android.support.test.runner.AndroidJUnit4;
import org.gnucash.android.R;
import org.gnucash.android.db.BookDbHelper;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.model.Book;
import org.gnucash.android.test.ui.util.DisableAnimationsRule;
import org.gnucash.android.ui.account.AccountsActivity;
import org.gnucash.android.ui.settings.PreferenceActivity;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.swipeUp;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent;
import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.allOf;
/**
* Test support for multiple books in the application
*/
@RunWith(AndroidJUnit4.class)
public class MultiBookTest {
private static BooksDbAdapter mBooksDbAdapter;
@Rule public GrantPermissionRule animationPermissionsRule = GrantPermissionRule.grant(Manifest.permission.SET_ANIMATION_SCALE);
@ClassRule
public static DisableAnimationsRule disableAnimationsRule = new DisableAnimationsRule();
@Rule
public IntentsTestRule<AccountsActivity> mActivityRule = new IntentsTestRule<>(AccountsActivity.class);
@BeforeClass
public static void prepTestCase(){
mBooksDbAdapter = BooksDbAdapter.getInstance();
}
@Test
public void shouldOpenBookManager(){
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.book_name)).check(matches(isDisplayed())).perform(click());
onView(withText(R.string.menu_manage_books)).perform(click());
Intents.intended(hasComponent(PreferenceActivity.class.getName()));
}
public void testLoadBookFromBookManager(){
Book book = new Book();
book.setDisplayName("Launch Codes");
BooksDbAdapter.getInstance().addRecord(book);
shouldOpenBookManager();
onView(withText(book.getDisplayName())).perform(click());
assertThat(BooksDbAdapter.getInstance().getActiveBookUID()).isEqualTo(book.getUID());
}
@Test
public void creatingNewAccounts_shouldCreatedNewBook(){
long booksCount = mBooksDbAdapter.getRecordsCount();
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.drawer_layout)).perform(swipeUp());
onView(withText(R.string.title_settings)).perform(click());
Intents.intended(hasComponent(PreferenceActivity.class.getName()));
onView(withText(R.string.header_account_settings)).perform(click());
onView(withText(R.string.title_create_default_accounts)).perform(click());
onView(withId(android.R.id.button1)).perform(click());
//// TODO: 18.05.2016 wait for import to finish instead
sleep(2000); //give import time to finish
assertThat(mBooksDbAdapter.getRecordsCount()).isEqualTo(booksCount+1);
//// TODO: 25.08.2016 Delete all books before the start of this test
Book activeBook = mBooksDbAdapter.getRecord(mBooksDbAdapter.getActiveBookUID());
assertThat(activeBook.getDisplayName()).isEqualTo("Book " + (booksCount+1));
}
@Test
public void testCreateNewBook(){
long bookCount = mBooksDbAdapter.getRecordsCount();
shouldOpenBookManager();
onView(withId(R.id.menu_create_book))
.check(matches(isDisplayed()))
.perform(click());
assertThat(mBooksDbAdapter.getRecordsCount()).isEqualTo(bookCount+1);
}
//TODO: Finish implementation of this test
public void testDeleteBook(){
long bookCount = mBooksDbAdapter.getRecordsCount();
Book book = new Book();
String displayName = "To Be Deleted";
book.setDisplayName(displayName);
mBooksDbAdapter.addRecord(book);
assertThat(mBooksDbAdapter.getRecordsCount()).isEqualTo(bookCount + 1);
shouldOpenBookManager();
onView(allOf(withParent(hasDescendant(withText(displayName))),
withId(R.id.options_menu))).perform(click());
onView(withText(R.string.menu_delete)).perform(click());
onView(withText(R.string.btn_delete_book)).perform(click());
assertThat(mBooksDbAdapter.getRecordsCount()).isEqualTo(bookCount);
}
private static void sleep(long millis){
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 6,107 | 37.175 | 131 |
java
|
gnucash-android
|
gnucash-android-master/app/src/androidTest/java/org/gnucash/android/test/ui/OwnCloudExportTest.java
|
/*
* Copyright (c) 2016 Felipe Morato <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.test.ui;
import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.contrib.DrawerActions;
import android.support.test.rule.ActivityTestRule;
import android.support.test.rule.GrantPermissionRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseHelper;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.Split;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.ui.account.AccountsActivity;
import org.junit.Assume;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.clearText;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.swipeUp;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static org.gnucash.android.test.ui.AccountsActivityTest.preventFirstRunDialogs;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OwnCloudExportTest {
private AccountsActivity mAccountsActivity;
private SharedPreferences mPrefs;
private String OC_SERVER = "https://demo.owncloud.org";
private String OC_USERNAME = "test";
private String OC_PASSWORD = "test";
private String OC_DIR = "gc_test";
/**
* A JUnit {@link Rule @Rule} to launch your activity under test. This is a replacement
* for {@link ActivityInstrumentationTestCase2}.
* <p>
* Rules are interceptors which are executed for each test method and will run before
* any of your setup code in the {@link Before @Before} method.
* <p>
* {@link ActivityTestRule} will create and launch of the activity for you and also expose
* the activity under test. To get a reference to the activity you can use
* the {@link ActivityTestRule#getActivity()} method.
*/
@Rule
public ActivityTestRule<AccountsActivity> mActivityRule = new ActivityTestRule<>(
AccountsActivity.class);
@Rule public GrantPermissionRule animationPermissionsRule = GrantPermissionRule.grant(Manifest.permission.SET_ANIMATION_SCALE);
@Before
public void setUp() throws Exception {
mAccountsActivity = mActivityRule.getActivity();
mPrefs = mAccountsActivity.getSharedPreferences(
mAccountsActivity.getString(R.string.owncloud_pref), Context.MODE_PRIVATE);
preventFirstRunDialogs(getInstrumentation().getTargetContext());
// creates Account and transaction
String activeBookUID = BooksDbAdapter.getInstance().getActiveBookUID();
DatabaseHelper mDbHelper = new DatabaseHelper(mAccountsActivity, activeBookUID);
SQLiteDatabase mDb;
try {
mDb = mDbHelper.getWritableDatabase();
} catch (SQLException e) {
Log.e(getClass().getName(), "Error getting database: " + e.getMessage());
mDb = mDbHelper.getReadableDatabase();
}
@SuppressWarnings("unused") //this call initializes constants in Commodity
CommoditiesDbAdapter commoditiesDbAdapter = new CommoditiesDbAdapter(mDb);
AccountsDbAdapter mAccountsDbAdapter = AccountsDbAdapter.getInstance();
mAccountsDbAdapter.deleteAllRecords();
String currencyCode = GnuCashApplication.getDefaultCurrencyCode();
Commodity.DEFAULT_COMMODITY = CommoditiesDbAdapter.getInstance().getCommodity(currencyCode);
Account account = new Account("ownCloud");
Transaction transaction = new Transaction("birds");
transaction.setTime(System.currentTimeMillis());
Split split = new Split(new Money("11.11", currencyCode), account.getUID());
transaction.addSplit(split);
transaction.addSplit(split.createPair(
mAccountsDbAdapter.getOrCreateImbalanceAccountUID(Commodity.DEFAULT_COMMODITY)));
account.addTransaction(transaction);
mAccountsDbAdapter.addRecord(account, DatabaseAdapter.UpdateMethod.insert);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mAccountsActivity.getString(R.string.key_owncloud_sync), false).apply();
editor.putInt(mAccountsActivity.getString(R.string.key_last_export_destination), 0);
editor.apply();
}
/**
* Test if there is an active internet connection on the device/emulator
* @return {@code true} is an internet connection is available, {@code false} otherwise
*/
public static boolean hasActiveInternetConnection(){
ConnectivityManager connectivityManager
= (ConnectivityManager) GnuCashApplication.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/**
* It might fail if it takes too long to connect to the server or if there is no network
*/
@Test
public void OwnCloudCredentials() {
Assume.assumeTrue(hasActiveInternetConnection());
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(swipeUp());
onView(withText(R.string.title_settings)).perform(click());
onView(withText(R.string.header_backup_and_export_settings)).perform(click());
onView(withText(R.string.title_owncloud_sync_preference)).perform(click());
onView(withId(R.id.owncloud_hostname)).check(matches(isDisplayed()));
onView(withId(R.id.owncloud_hostname)).perform(clearText()).perform(typeText(OC_SERVER), closeSoftKeyboard());
onView(withId(R.id.owncloud_username)).perform(clearText()).perform(typeText(OC_USERNAME), closeSoftKeyboard());
onView(withId(R.id.owncloud_password)).perform(clearText()).perform(typeText(OC_PASSWORD), closeSoftKeyboard());
onView(withId(R.id.owncloud_dir)).perform(clearText()).perform(typeText(OC_DIR), closeSoftKeyboard());
onView(withId(R.id.btn_save)).perform(click());
sleep(5000);
onView(withId(R.id.btn_save)).perform(click());
assertEquals(mPrefs.getString(mAccountsActivity.getString(R.string.key_owncloud_server), null), OC_SERVER);
assertEquals(mPrefs.getString(mAccountsActivity.getString(R.string.key_owncloud_username), null), OC_USERNAME);
assertEquals(mPrefs.getString(mAccountsActivity.getString(R.string.key_owncloud_password), null), OC_PASSWORD);
assertEquals(mPrefs.getString(mAccountsActivity.getString(R.string.key_owncloud_dir), null), OC_DIR);
assertTrue(mPrefs.getBoolean(mAccountsActivity.getString(R.string.key_owncloud_sync), false));
}
//// FIXME: 20.04.2017 This test now fails since introduction of SAF.
public void OwnCloudExport() {
Assume.assumeTrue(hasActiveInternetConnection());
mPrefs.edit().putBoolean(mAccountsActivity.getString(R.string.key_owncloud_sync), true).commit();
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withText(R.string.nav_menu_export)).perform(click());
Espresso.closeSoftKeyboard();
Espresso.pressBack(); //close the SAF file picker window
onView(withId(R.id.spinner_export_destination)).perform(click());
String[] destinations = mAccountsActivity.getResources().getStringArray(R.array.export_destinations);
onView(withText(destinations[3])).perform(click());
onView(withId(R.id.menu_save)).perform(click());
assertToastDisplayed(String.format(mAccountsActivity.getString(R.string.toast_exported_to), "ownCloud -> " + OC_DIR));
}
/**
* Checks that a specific toast message is displayed
* @param toastString String that should be displayed
*/
private void assertToastDisplayed(String toastString) {
onView(withText(toastString))
.inRoot(withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView()))))
.check(matches(isDisplayed()));
}
/**
* Sleep the thread for a specified period
* @param millis Duration to sleep in milliseconds
*/
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 10,681 | 45.646288 | 131 |
java
|
gnucash-android
|
gnucash-android-master/app/src/androidTest/java/org/gnucash/android/test/ui/PieChartReportTest.java
|
/*
* Copyright (c) 2015 Oleksandr Tyshkovets <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.test.ui;
import android.Manifest;
import android.content.Context;
import android.support.test.espresso.ViewAction;
import android.support.test.espresso.action.CoordinatesProvider;
import android.support.test.espresso.action.GeneralClickAction;
import android.support.test.espresso.action.Press;
import android.support.test.espresso.action.Tap;
import android.support.test.rule.ActivityTestRule;
import android.support.test.rule.GrantPermissionRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.View;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.importer.GncXmlImporter;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.Split;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.model.TransactionType;
import org.gnucash.android.test.ui.util.DisableAnimationsRule;
import org.gnucash.android.ui.report.BaseReportFragment;
import org.gnucash.android.ui.report.ReportsActivity;
import org.gnucash.android.ui.report.piechart.PieChartFragment;
import org.gnucash.android.ui.settings.PreferenceActivity;
import org.gnucash.android.util.BookUtils;
import org.joda.time.LocalDateTime;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.math.BigDecimal;
import java.util.Locale;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(AndroidJUnit4.class)
public class PieChartReportTest {
public static final String TAG = PieChartReportTest.class.getName();
private static final String TRANSACTION_NAME = "Pizza";
private static final double TRANSACTION_AMOUNT = 9.99;
private static final String TRANSACTION2_NAME = "1984";
private static final double TRANSACTION2_AMOUNT = 12.49;
private static final String TRANSACTION3_NAME = "Nice gift";
private static final double TRANSACTION3_AMOUNT = 2000.00;
private static final String CASH_IN_WALLET_ASSET_ACCOUNT_UID = "b687a487849470c25e0ff5aaad6a522b";
private static final String DINING_EXPENSE_ACCOUNT_UID = "62922c5ccb31d6198259739d27d858fe";
private static final String DINING_EXPENSE_ACCOUNT_NAME = "Dining";
private static final String BOOKS_EXPENSE_ACCOUNT_UID = "a8b342435aceac7c3cac214f9385dd72";
private static final String BOOKS_EXPENSE_ACCOUNT_NAME = "Books";
private static final String GIFTS_RECEIVED_INCOME_ACCOUNT_UID = "b01950c0df0890b6543209d51c8e0b0f";
private static final String GIFTS_RECEIVED_INCOME_ACCOUNT_NAME = "Gifts Received";
public static Commodity CURRENCY;
private static AccountsDbAdapter mAccountsDbAdapter;
private static TransactionsDbAdapter mTransactionsDbAdapter;
private ReportsActivity mReportsActivity;
@Rule
public ActivityTestRule<ReportsActivity> mActivityRule = new ActivityTestRule<>(ReportsActivity.class);
@Rule public GrantPermissionRule animationPermissionsRule = GrantPermissionRule.grant(Manifest.permission.SET_ANIMATION_SCALE);
@ClassRule
public static DisableAnimationsRule disableAnimationsRule = new DisableAnimationsRule();
private static String testBookUID;
private static String oldActiveBookUID;
public PieChartReportTest() {
//nothing to se here, move along
CURRENCY = new Commodity("US Dollars", "USD", 100);
}
@BeforeClass
public static void prepareTestCase() throws Exception {
Context context = GnuCashApplication.getAppContext();
oldActiveBookUID = BooksDbAdapter.getInstance().getActiveBookUID();
testBookUID = GncXmlImporter.parse(context.getResources().openRawResource(R.raw.default_accounts));
BookUtils.loadBook(testBookUID);
mTransactionsDbAdapter = TransactionsDbAdapter.getInstance();
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
CURRENCY = CommoditiesDbAdapter.getInstance().getCommodity("USD");
PreferenceActivity.getActiveBookSharedPreferences().edit()
.putString(context.getString(R.string.key_default_currency), CURRENCY.getCurrencyCode())
.commit();
}
@Before
public void setUp() throws Exception {
mTransactionsDbAdapter.deleteAllRecords();
mReportsActivity = mActivityRule.getActivity();
assertThat(mAccountsDbAdapter.getRecordsCount()).isGreaterThan(20); //lots of accounts in the default
onView(withId(R.id.btn_pie_chart)).perform(click());
}
/**
* Add a transaction for the current month in order to test the report view
* @throws Exception
*/
private void addTransactionForCurrentMonth() throws Exception {
Transaction transaction = new Transaction(TRANSACTION_NAME);
transaction.setTime(System.currentTimeMillis());
Split split = new Split(new Money(BigDecimal.valueOf(TRANSACTION_AMOUNT), CURRENCY), DINING_EXPENSE_ACCOUNT_UID);
split.setType(TransactionType.DEBIT);
transaction.addSplit(split);
transaction.addSplit(split.createPair(CASH_IN_WALLET_ASSET_ACCOUNT_UID));
mTransactionsDbAdapter.addRecord(transaction, DatabaseAdapter.UpdateMethod.insert);
}
/**
* Add a transactions for the previous month for testing pie chart
* @param minusMonths Number of months prior
*/
private void addTransactionForPreviousMonth(int minusMonths) {
Transaction transaction = new Transaction(TRANSACTION2_NAME);
transaction.setTime(new LocalDateTime().minusMonths(minusMonths).toDate().getTime());
Split split = new Split(new Money(BigDecimal.valueOf(TRANSACTION2_AMOUNT), CURRENCY), BOOKS_EXPENSE_ACCOUNT_UID);
split.setType(TransactionType.DEBIT);
transaction.addSplit(split);
transaction.addSplit(split.createPair(CASH_IN_WALLET_ASSET_ACCOUNT_UID));
mTransactionsDbAdapter.addRecord(transaction, DatabaseAdapter.UpdateMethod.insert);
}
@Test
public void testNoData() {
onView(withId(R.id.pie_chart)).perform(click());
onView(withId(R.id.selected_chart_slice)).check(matches(withText(R.string.label_select_pie_slice_to_see_details)));
}
@Test
public void testSelectingValue() throws Exception {
addTransactionForCurrentMonth();
addTransactionForPreviousMonth(1);
refreshReport();
onView(withId(R.id.pie_chart)).perform(clickXY(Position.BEGIN, Position.MIDDLE));
float percent = (float) (TRANSACTION_AMOUNT / (TRANSACTION_AMOUNT + TRANSACTION2_AMOUNT) * 100);
String selectedText = String.format(Locale.US, BaseReportFragment.SELECTED_VALUE_PATTERN, DINING_EXPENSE_ACCOUNT_NAME, TRANSACTION_AMOUNT, percent);
onView(withId(R.id.selected_chart_slice)).check(matches(withText(selectedText)));
}
@Test
public void testSpinner() throws Exception {
Split split = new Split(new Money(BigDecimal.valueOf(TRANSACTION3_AMOUNT), CURRENCY), GIFTS_RECEIVED_INCOME_ACCOUNT_UID);
Transaction transaction = new Transaction(TRANSACTION3_NAME);
transaction.addSplit(split);
transaction.addSplit(split.createPair(CASH_IN_WALLET_ASSET_ACCOUNT_UID));
mTransactionsDbAdapter.addRecord(transaction, DatabaseAdapter.UpdateMethod.insert);
refreshReport();
Thread.sleep(1000);
onView(withId(R.id.report_account_type_spinner)).perform(click());
onView(withText(AccountType.INCOME.name())).perform(click());
onView(withId(R.id.pie_chart)).perform(clickXY(Position.BEGIN, Position.MIDDLE));
String selectedText = String.format(PieChartFragment.SELECTED_VALUE_PATTERN, GIFTS_RECEIVED_INCOME_ACCOUNT_NAME, TRANSACTION3_AMOUNT, 100f);
onView(withId(R.id.selected_chart_slice)).check(matches(withText(selectedText)));
onView(withId(R.id.report_account_type_spinner)).perform(click());
onView(withText(AccountType.EXPENSE.name())).perform(click());
onView(withId(R.id.pie_chart)).perform(click());
onView(withId(R.id.selected_chart_slice)).check(matches(withText(R.string.label_select_pie_slice_to_see_details)));
}
public static ViewAction clickXY(final Position horizontal, final Position vertical){
return new GeneralClickAction(
Tap.SINGLE,
new CoordinatesProvider() {
@Override
public float[] calculateCoordinates(View view) {
int[] xy = new int[2];
view.getLocationOnScreen(xy);
float x = horizontal.getPosition(xy[0], view.getWidth());
float y = vertical.getPosition(xy[1], view.getHeight());
return new float[]{x, y};
}
},
Press.FINGER);
}
private enum Position {
BEGIN {
@Override
public float getPosition(int viewPos, int viewLength) {
return viewPos + (viewLength * 0.15f);
}
},
MIDDLE {
@Override
public float getPosition(int viewPos, int viewLength) {
return viewPos + (viewLength * 0.5f);
}
},
END {
@Override
public float getPosition(int viewPos, int viewLength) {
return viewPos + (viewLength * 0.85f);
}
};
abstract float getPosition(int widgetPos, int widgetLength);
}
/**
* Refresh reports
*/
private void refreshReport(){
try {
mActivityRule.runOnUiThread(new Runnable() {
@Override
public void run() {
mReportsActivity.refresh();
}
});
} catch (Throwable t){
System.err.println("Faile to refresh reports");
}
}
@After
public void tearDown() throws Exception {
mReportsActivity.finish();
}
@AfterClass
public static void cleanup(){
BooksDbAdapter booksDbAdapter = BooksDbAdapter.getInstance();
booksDbAdapter.setActive(oldActiveBookUID);
booksDbAdapter.deleteRecord(testBookUID);
}
}
| 11,712 | 38.976109 | 156 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.