Skip to content

Commit

Permalink
Work on #381, added draft implementation of service stub pattern. Doi…
Browse files Browse the repository at this point in the history
…ng this to help @jdoetricksy get the hang of abstractions
  • Loading branch information
npathai committed Aug 7, 2016
1 parent d50139e commit 65adc09
Show file tree
Hide file tree
Showing 13 changed files with 435 additions and 0 deletions.
52 changes: 52 additions & 0 deletions service-stub/pom.xml
@@ -0,0 +1,52 @@
<?xml version="1.0"?>
<!--
The MIT License
Copyright (c) 2014 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.13.0-SNAPSHOT</version>
</parent>
<artifactId>service-stub</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.yahoofinance-api</groupId>
<artifactId>YahooFinanceAPI</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,34 @@
package com.iluwatar.servicestub.service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class App {

public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();

try {
YahooStockService service = new YahooStockService();

Portfolio portfolio = new Portfolio("iluwatar");
BuyAtCurrentPriceCommand googleCurrentPriceBuy = new BuyAtCurrentPriceCommand(service, portfolio,
new Stock("GOOG", "Google"), 100);
googleCurrentPriceBuy.execute();

BuyAtCurrentPriceCommand yahooCurrentPriceBuy = new BuyAtCurrentPriceCommand(service, portfolio,
new Stock("YHOO", "Yahoo"), 100);
yahooCurrentPriceBuy.execute();

BuyAtLimitPriceCommand yahooLimitPriceBuy = new BuyAtLimitPriceCommand(service, portfolio,
new Stock("YHOO", "Yahoo"), 100,service.getQuote(new Stock("YHOO", "Yahoo")).getCurrentPrice(),
executor);

yahooLimitPriceBuy.execute().get();

System.out.println(portfolio);
} finally {
executor.shutdownNow();
}
}
}
@@ -0,0 +1,31 @@
package com.iluwatar.servicestub.service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

public class BuyAtCurrentPriceCommand {

private StockService service;
private Portfolio portfolio;
private Stock stock;
private int quantity;

public BuyAtCurrentPriceCommand(StockService service, Portfolio portfolio, Stock stock, int quantity) {
this.service = service;
this.portfolio = portfolio;
this.stock = stock;
this.quantity = quantity;
}

public Future<Void> execute() {
try {
StockQuote stockQuote = service.getQuote(stock);
portfolio.add(stock, quantity, stockQuote.getCurrentPrice());
return CompletableFuture.completedFuture(null);
} catch (Exception e) {
CompletableFuture<Void> future = new CompletableFuture<>();
future.completeExceptionally(e);
return future;
}
}
}
@@ -0,0 +1,51 @@
package com.iluwatar.servicestub.service;

import java.math.BigDecimal;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class BuyAtLimitPriceCommand {
private StockService service;
private Portfolio portfolio;
private Stock stock;
private int quantity;
private BigDecimal priceLimit;
private Executor executor;

public BuyAtLimitPriceCommand(StockService service, Portfolio portfolio, Stock stock,
int quantity, BigDecimal priceLimit,
Executor executor) {
this.service = service;
this.portfolio = portfolio;
this.stock = stock;
this.quantity = quantity;
this.priceLimit = priceLimit;
this.executor = executor;
}

public Future<Void> execute() {
CompletableFuture<Void> future = new CompletableFuture<>();
executor.execute(() -> {
try {
while (true) {
StockQuote stockQuote = service.getQuote(stock);

if (stockQuote.getCurrentPrice().compareTo(priceLimit) <= 0) {
portfolio.add(stock, quantity, stockQuote.getCurrentPrice());
future.complete(null);
break;
} else {
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
}
}

} catch (Exception e) {
future.completeExceptionally(e);
}

});
return future;
}
}
@@ -0,0 +1,44 @@
package com.iluwatar.servicestub.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class Portfolio {

private final String username;
private final Map<Stock, StockInformation> stockToStockInformation = new HashMap<>();
private BigDecimal totalAssets;

public Portfolio(String username) {
this.username = username;
this.totalAssets = new BigDecimal(0);
}

public void add(Stock stock, int quantity, BigDecimal price) {
StockInformation stockInformation = stockToStockInformation.get(stock);
if (stockInformation == null) {
stockInformation = new StockInformation(stock, price, quantity);
stockToStockInformation.put(stock, stockInformation);
} else {
stockInformation.add(quantity, price);
}
totalAssets = totalAssets.add(price.multiply(new BigDecimal(quantity)));
}

@Override
public String toString() {

StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(String.format("User: %s | Total assets worth: %f%n", username, totalAssets.floatValue()));
for (StockInformation stockInformation : stockToStockInformation.values()) {
stringBuilder.append(stockInformation.toString()).append("\n");
}

return stringBuilder.toString();
}

public StockInformation get(Stock stock) {
return stockToStockInformation.get(stock);
}
}
@@ -0,0 +1,6 @@
package com.iluwatar.servicestub.service;

public class SellCommand {


}
@@ -0,0 +1,48 @@
package com.iluwatar.servicestub.service;

public class Stock {

private final String symbol;
private final String name;

public Stock(String symbol, String name) {
this.symbol = symbol;
this.name = name;
}

public String getSymbol() {
return symbol;
}

public String getName() {
return name;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((symbol == null) ? 0 : symbol.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Stock other = (Stock) obj;
if (symbol == null) {
if (other.symbol != null)
return false;
} else if (!symbol.equals(other.symbol))
return false;
return true;
}



}
@@ -0,0 +1,39 @@
package com.iluwatar.servicestub.service;

import java.math.BigDecimal;

public class StockInformation {

private final Stock stock;
private BigDecimal totalStockPrice;
private int quantity;


public StockInformation(Stock stock, BigDecimal buyPrice, int quantity) {
this.stock = stock;
this.totalStockPrice = buyPrice.multiply(new BigDecimal(quantity));
this.quantity = quantity;
}

public Stock getStock() {
return stock;
}

public BigDecimal getAverageStockPrice() {
return totalStockPrice.divide(new BigDecimal(quantity));
}

public int getQuantity() {
return quantity;
}

public void add(int quantity, BigDecimal price) {
this.quantity += quantity;
this.totalStockPrice = totalStockPrice.add(price.multiply(new BigDecimal(quantity)));
}

@Override
public String toString() {
return String.format("Stock: %s | Quantity: %d | Avg.Price: %f", stock.getName(), quantity, getAverageStockPrice().floatValue());
}
}
@@ -0,0 +1,23 @@
package com.iluwatar.servicestub.service;

import java.math.BigDecimal;

public class StockQuote {

private final BigDecimal currentPrice;

public StockQuote(BigDecimal currentPrice) {
this.currentPrice = currentPrice;
}


public BigDecimal getCurrentPrice() {
return currentPrice;
}

@Override
public String toString() {
return String.format("Current trading price: %f", currentPrice.floatValue());
}

}
@@ -0,0 +1,6 @@
package com.iluwatar.servicestub.service;

public interface StockService {

StockQuote getQuote(Stock stock) throws Exception;
}
@@ -0,0 +1,20 @@
package com.iluwatar.servicestub.service;

import java.math.BigDecimal;

public class StockServiceStub implements StockService {
private StockQuote quote;

public StockServiceStub(BigDecimal quotePrice) {
this.quote = new StockQuote(quotePrice);
}

@Override
public StockQuote getQuote(Stock stock) throws Exception {
return quote;
}

public void setQuotePrice(BigDecimal quotePrice) {
this.quote = new StockQuote(quotePrice);
}
}
@@ -0,0 +1,14 @@
package com.iluwatar.servicestub.service;

import yahoofinance.Stock;
import yahoofinance.YahooFinance;

public class YahooStockService implements StockService {

@Override
public StockQuote getQuote(com.iluwatar.servicestub.service.Stock stock) throws Exception {
Stock yahooStock = YahooFinance.get(stock.getSymbol());
return new StockQuote(yahooStock.getQuote().getPrice());
}

}

0 comments on commit 65adc09

Please sign in to comment.