proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
iluwatar_java-design-patterns
|
java-design-patterns/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java
|
PriceClientImpl
|
getPrice
|
class PriceClientImpl implements PriceClient {
/**
* Makes a simple HTTP Get request to the Price microservice.
*
* @return The price of the product
*/
@Override
public String getPrice() {<FILL_FUNCTION_BODY>}
private void logResponse(HttpResponse<String> httpResponse) {
if (isSuccessResponse(httpResponse.statusCode())) {
LOGGER.info("Price info received successfully");
} else {
LOGGER.warn("Price info request failed");
}
}
private boolean isSuccessResponse(int responseCode) {
return responseCode >= 200 && responseCode <= 299;
}
}
|
var httpClient = HttpClient.newHttpClient();
var httpGet = HttpRequest.newBuilder()
.GET()
.uri(URI.create("http://localhost:50006/price"))
.build();
try {
LOGGER.info("Sending request to fetch price info");
var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString());
logResponse(httpResponse);
return httpResponse.body();
} catch (IOException e) {
LOGGER.error("Failure occurred while getting price info", e);
} catch (InterruptedException e) {
LOGGER.error("Failure occurred while getting price info", e);
Thread.currentThread().interrupt();
}
return null;
| 172
| 187
| 359
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/arrange-act-assert/src/main/java/com/iluwatar/arrangeactassert/Cash.java
|
Cash
|
minus
|
class Cash {
private int amount;
//plus
void plus(int addend) {
amount += addend;
}
//minus
boolean minus(int subtrahend) {<FILL_FUNCTION_BODY>}
//count
int count() {
return amount;
}
}
|
if (amount >= subtrahend) {
amount -= subtrahend;
return true;
} else {
return false;
}
| 85
| 41
| 126
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java
|
App
|
main
|
class App {
private static final String ROCKET_LAUNCH_LOG_PATTERN = "Space rocket <%s> launched successfully";
/**
* Program entry point.
*/
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
/**
* Creates a callable that lazily evaluates to given value with artificial delay.
*
* @param value value to evaluate
* @param delayMillis artificial delay in milliseconds
* @return new callable for lazy evaluation
*/
private static <T> Callable<T> lazyval(T value, long delayMillis) {
return () -> {
Thread.sleep(delayMillis);
log(String.format(ROCKET_LAUNCH_LOG_PATTERN, value));
return value;
};
}
/**
* Creates a simple callback that logs the complete status of the async result.
*
* @param name callback name
* @return new async callback
*/
private static <T> AsyncCallback<T> callback(String name) {
return new AsyncCallback<>() {
@Override
public void onComplete(T value) {
log(name + " <" + value + ">");
}
@Override
public void onError(Exception ex) {
log(name + " failed: " + ex.getMessage());
}
};
}
private static void log(String msg) {
LOGGER.info(msg);
}
}
|
// construct a new executor that will run async tasks
var executor = new ThreadAsyncExecutor();
// start few async tasks with varying processing times, two last with callback handlers
final var asyncResult1 = executor.startProcess(lazyval(10, 500));
final var asyncResult2 = executor.startProcess(lazyval("test", 300));
final var asyncResult3 = executor.startProcess(lazyval(50L, 700));
final var asyncResult4 = executor.startProcess(lazyval(20, 400),
callback("Deploying lunar rover"));
final var asyncResult5 =
executor.startProcess(lazyval("callback", 600), callback("Deploying lunar rover"));
// emulate processing in the current thread while async tasks are running in their own threads
Thread.sleep(350); // Oh boy, we are working hard here
log("Mission command is sipping coffee");
// wait for completion of the tasks
final var result1 = executor.endProcess(asyncResult1);
final var result2 = executor.endProcess(asyncResult2);
final var result3 = executor.endProcess(asyncResult3);
asyncResult4.await();
asyncResult5.await();
// log the results of the tasks, callbacks log immediately when complete
log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result1));
log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result2));
log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result3));
| 391
| 421
| 812
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java
|
CompletableResult
|
setException
|
class CompletableResult<T> implements AsyncResult<T> {
static final int RUNNING = 1;
static final int FAILED = 2;
static final int COMPLETED = 3;
final Object lock;
final AsyncCallback<T> callback;
volatile int state = RUNNING;
T value;
Exception exception;
CompletableResult(AsyncCallback<T> callback) {
this.lock = new Object();
this.callback = callback;
}
boolean hasCallback() {
return callback != null;
}
/**
* Sets the value from successful execution and executes callback if available. Notifies any
* thread waiting for completion.
*
* @param value value of the evaluated task
*/
void setValue(T value) {
this.value = value;
this.state = COMPLETED;
if (hasCallback()) {
callback.onComplete(value);
}
synchronized (lock) {
lock.notifyAll();
}
}
/**
* Sets the exception from failed execution and executes callback if available. Notifies any
* thread waiting for completion.
*
* @param exception exception of the failed task
*/
void setException(Exception exception) {<FILL_FUNCTION_BODY>}
@Override
public boolean isCompleted() {
return state > RUNNING;
}
@Override
public T getValue() throws ExecutionException {
if (state == COMPLETED) {
return value;
} else if (state == FAILED) {
throw new ExecutionException(exception);
} else {
throw new IllegalStateException("Execution not completed yet");
}
}
@Override
public void await() throws InterruptedException {
synchronized (lock) {
while (!isCompleted()) {
lock.wait();
}
}
}
}
|
this.exception = exception;
this.state = FAILED;
if (hasCallback()) {
callback.onError(exception);
}
synchronized (lock) {
lock.notifyAll();
}
| 493
| 59
| 552
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/balking/src/main/java/com/iluwatar/balking/App.java
|
App
|
main
|
class App {
/**
* Entry Point.
*
* @param args the command line arguments - not used
*/
public static void main(String... args) {<FILL_FUNCTION_BODY>}
}
|
final var washingMachine = new WashingMachine();
var executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 3; i++) {
executorService.execute(washingMachine::wash);
}
executorService.shutdown();
try {
if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException ie) {
LOGGER.error("ERROR: Waiting on executor service shutdown!");
Thread.currentThread().interrupt();
}
| 59
| 160
| 219
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/balking/src/main/java/com/iluwatar/balking/WashingMachine.java
|
WashingMachine
|
wash
|
class WashingMachine {
private final DelayProvider delayProvider;
@Getter
private WashingMachineState washingMachineState;
/**
* Creates a new instance of WashingMachine.
*/
public WashingMachine() {
this((interval, timeUnit, task) -> {
try {
Thread.sleep(timeUnit.toMillis(interval));
} catch (InterruptedException ie) {
LOGGER.error("", ie);
Thread.currentThread().interrupt();
}
task.run();
});
}
/**
* Creates a new instance of WashingMachine using provided delayProvider. This constructor is used
* only for unit testing purposes.
*/
public WashingMachine(DelayProvider delayProvider) {
this.delayProvider = delayProvider;
this.washingMachineState = WashingMachineState.ENABLED;
}
/**
* Method responsible for washing if the object is in appropriate state.
*/
public void wash() {<FILL_FUNCTION_BODY>}
/**
* Method is responsible for ending the washing by changing machine state.
*/
public synchronized void endOfWashing() {
washingMachineState = WashingMachineState.ENABLED;
LOGGER.info("{}: Washing completed.", Thread.currentThread().getId());
}
}
|
synchronized (this) {
var machineState = getWashingMachineState();
LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), machineState);
if (this.washingMachineState == WashingMachineState.WASHING) {
LOGGER.error("Cannot wash if the machine has been already washing!");
return;
}
this.washingMachineState = WashingMachineState.WASHING;
}
LOGGER.info("{}: Doing the washing", Thread.currentThread().getName());
this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing);
| 338
| 168
| 506
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/bridge/src/main/java/com/iluwatar/bridge/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("The knight receives an enchanted sword.");
var enchantedSword = new Sword(new SoulEatingEnchantment());
enchantedSword.wield();
enchantedSword.swing();
enchantedSword.unwield();
LOGGER.info("The valkyrie receives an enchanted hammer.");
var hammer = new Hammer(new FlyingEnchantment());
hammer.wield();
hammer.swing();
hammer.unwield();
| 56
| 129
| 185
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java
|
FlyingEnchantment
|
apply
|
class FlyingEnchantment implements Enchantment {
@Override
public void onActivate() {
LOGGER.info("The item begins to glow faintly.");
}
@Override
public void apply() {<FILL_FUNCTION_BODY>}
@Override
public void onDeactivate() {
LOGGER.info("The item's glow fades.");
}
}
|
LOGGER.info("The item flies and strikes the enemies finally returning to owner's hand.");
| 103
| 26
| 129
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/builder/src/main/java/com/iluwatar/builder/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var mage = new Hero.Builder(Profession.MAGE, "Riobard")
.withHairColor(HairColor.BLACK)
.withWeapon(Weapon.DAGGER)
.build();
LOGGER.info(mage.toString());
var warrior = new Hero.Builder(Profession.WARRIOR, "Amberjill")
.withHairColor(HairColor.BLOND)
.withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD)
.build();
LOGGER.info(warrior.toString());
var thief = new Hero.Builder(Profession.THIEF, "Desmond")
.withHairType(HairType.BALD)
.withWeapon(Weapon.BOW)
.build();
LOGGER.info(thief.toString());
| 56
| 252
| 308
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// prepare the objects
var businessDelegate = new BusinessDelegate();
var businessLookup = new BusinessLookup();
businessLookup.setNetflixService(new NetflixService());
businessLookup.setYouTubeService(new YouTubeService());
businessDelegate.setLookupService(businessLookup);
// create the client and use the business delegate
var client = new MobileClient(businessDelegate);
client.playbackMovie("Die Hard 2");
client.playbackMovie("Maradona: The Greatest Ever");
| 56
| 134
| 190
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java
|
BusinessLookup
|
getBusinessService
|
class BusinessLookup {
private NetflixService netflixService;
private YouTubeService youTubeService;
/**
* Gets service instance based on given movie search string.
*
* @param movie Search string for the movie.
* @return Service instance.
*/
public VideoStreamingService getBusinessService(String movie) {<FILL_FUNCTION_BODY>}
}
|
if (movie.toLowerCase(Locale.ROOT).contains("die hard")) {
return netflixService;
} else {
return youTubeService;
}
| 99
| 48
| 147
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/bytecode/src/main/java/com/iluwatar/bytecode/App.java
|
App
|
main
|
class App {
private static final String LITERAL_0 = "LITERAL 0";
private static final String HEALTH_PATTERN = "%s_HEALTH";
private static final String GET_AGILITY = "GET_AGILITY";
private static final String GET_WISDOM = "GET_WISDOM";
private static final String ADD = "ADD";
private static final String LITERAL_2 = "LITERAL 2";
private static final String DIVIDE = "DIVIDE";
/**
* Main app method.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var vm = new VirtualMachine(
new Wizard(45, 7, 11, 0, 0),
new Wizard(36, 18, 8, 0, 0));
vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0));
vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0));
vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "GET")));
vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0));
vm.execute(InstructionConverterUtil.convertToByteCode(GET_AGILITY));
vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0));
vm.execute(InstructionConverterUtil.convertToByteCode(GET_WISDOM));
vm.execute(InstructionConverterUtil.convertToByteCode(ADD));
vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_2));
vm.execute(InstructionConverterUtil.convertToByteCode(DIVIDE));
vm.execute(InstructionConverterUtil.convertToByteCode(ADD));
vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "SET")));
| 178
| 331
| 509
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java
|
VirtualMachine
|
execute
|
class VirtualMachine {
private final Stack<Integer> stack = new Stack<>();
private final Wizard[] wizards = new Wizard[2];
/**
* No-args constructor.
*/
public VirtualMachine() {
wizards[0] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32),
0, 0);
wizards[1] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32),
0, 0);
}
/**
* Constructor taking the wizards as arguments.
*/
public VirtualMachine(Wizard wizard1, Wizard wizard2) {
wizards[0] = wizard1;
wizards[1] = wizard2;
}
/**
* Executes provided bytecode.
*
* @param bytecode to execute
*/
public void execute(int[] bytecode) {<FILL_FUNCTION_BODY>}
public void setHealth(int wizard, int amount) {
wizards[wizard].setHealth(amount);
}
public void setWisdom(int wizard, int amount) {
wizards[wizard].setWisdom(amount);
}
public void setAgility(int wizard, int amount) {
wizards[wizard].setAgility(amount);
}
public int getHealth(int wizard) {
return wizards[wizard].getHealth();
}
public int getWisdom(int wizard) {
return wizards[wizard].getWisdom();
}
public int getAgility(int wizard) {
return wizards[wizard].getAgility();
}
private int randomInt(int min, int max) {
return ThreadLocalRandom.current().nextInt(min, max + 1);
}
}
|
for (var i = 0; i < bytecode.length; i++) {
Instruction instruction = Instruction.getInstruction(bytecode[i]);
switch (instruction) {
case LITERAL:
// Read the next byte from the bytecode.
int value = bytecode[++i];
// Push the next value to stack
stack.push(value);
break;
case SET_AGILITY:
var amount = stack.pop();
var wizard = stack.pop();
setAgility(wizard, amount);
break;
case SET_WISDOM:
amount = stack.pop();
wizard = stack.pop();
setWisdom(wizard, amount);
break;
case SET_HEALTH:
amount = stack.pop();
wizard = stack.pop();
setHealth(wizard, amount);
break;
case GET_HEALTH:
wizard = stack.pop();
stack.push(getHealth(wizard));
break;
case GET_AGILITY:
wizard = stack.pop();
stack.push(getAgility(wizard));
break;
case GET_WISDOM:
wizard = stack.pop();
stack.push(getWisdom(wizard));
break;
case ADD:
var a = stack.pop();
var b = stack.pop();
stack.push(a + b);
break;
case DIVIDE:
a = stack.pop();
b = stack.pop();
stack.push(b / a);
break;
case PLAY_SOUND:
wizard = stack.pop();
getWizards()[wizard].playSound();
break;
case SPAWN_PARTICLES:
wizard = stack.pop();
getWizards()[wizard].spawnParticles();
break;
default:
throw new IllegalArgumentException("Invalid instruction value");
}
LOGGER.info("Executed " + instruction.name() + ", Stack contains " + getStack());
}
| 509
| 523
| 1,032
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java
|
InstructionConverterUtil
|
isValidInstruction
|
class InstructionConverterUtil {
/**
* Converts instructions represented as String.
*
* @param instructions to convert
* @return array of int representing bytecode
*/
public static int[] convertToByteCode(String instructions) {
if (instructions == null || instructions.trim().length() == 0) {
return new int[0];
}
var splitedInstructions = instructions.trim().split(" ");
var bytecode = new int[splitedInstructions.length];
for (var i = 0; i < splitedInstructions.length; i++) {
if (isValidInstruction(splitedInstructions[i])) {
bytecode[i] = Instruction.valueOf(splitedInstructions[i]).getIntValue();
} else if (isValidInt(splitedInstructions[i])) {
bytecode[i] = Integer.parseInt(splitedInstructions[i]);
} else {
var errorMessage = "Invalid instruction or number: " + splitedInstructions[i];
throw new IllegalArgumentException(errorMessage);
}
}
return bytecode;
}
private static boolean isValidInstruction(String instruction) {<FILL_FUNCTION_BODY>}
private static boolean isValidInt(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
try {
Instruction.valueOf(instruction);
return true;
} catch (IllegalArgumentException e) {
return false;
}
| 361
| 42
| 403
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/caching/src/main/java/com/iluwatar/caching/App.java
|
App
|
main
|
class App {
/**
* Constant parameter name to use mongoDB.
*/
private static final String USE_MONGO_DB = "--mongo";
/**
* Application manager.
*/
private final AppManager appManager;
/**
* Constructor of current App.
*
* @param isMongo boolean
*/
public App(final boolean isMongo) {
DbManager dbManager = DbManagerFactory.initDb(isMongo);
appManager = new AppManager(dbManager);
appManager.initDb();
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(final String[] args) {<FILL_FUNCTION_BODY>}
/**
* Check the input parameters. if
*
* @param args input params
* @return true if there is "--mongo" parameter in arguments
*/
private static boolean isDbMongo(final String[] args) {
for (String arg : args) {
if (arg.equals(USE_MONGO_DB)) {
return true;
}
}
return false;
}
/**
* Read-through and write-through.
*/
public void useReadAndWriteThroughStrategy() {
LOGGER.info("# CachingPolicy.THROUGH");
appManager.initCachingPolicy(CachingPolicy.THROUGH);
var userAccount1 = new UserAccount("001", "John", "He is a boy.");
appManager.save(userAccount1);
LOGGER.info(appManager.printCacheContent());
appManager.find("001");
appManager.find("001");
}
/**
* Read-through and write-around.
*/
public void useReadThroughAndWriteAroundStrategy() {
LOGGER.info("# CachingPolicy.AROUND");
appManager.initCachingPolicy(CachingPolicy.AROUND);
var userAccount2 = new UserAccount("002", "Jane", "She is a girl.");
appManager.save(userAccount2);
LOGGER.info(appManager.printCacheContent());
appManager.find("002");
LOGGER.info(appManager.printCacheContent());
userAccount2 = appManager.find("002");
userAccount2.setUserName("Jane G.");
appManager.save(userAccount2);
LOGGER.info(appManager.printCacheContent());
appManager.find("002");
LOGGER.info(appManager.printCacheContent());
appManager.find("002");
}
/**
* Read-through and write-behind.
*/
public void useReadThroughAndWriteBehindStrategy() {
LOGGER.info("# CachingPolicy.BEHIND");
appManager.initCachingPolicy(CachingPolicy.BEHIND);
var userAccount3 = new UserAccount("003",
"Adam",
"He likes food.");
var userAccount4 = new UserAccount("004",
"Rita",
"She hates cats.");
var userAccount5 = new UserAccount("005",
"Isaac",
"He is allergic to mustard.");
appManager.save(userAccount3);
appManager.save(userAccount4);
appManager.save(userAccount5);
LOGGER.info(appManager.printCacheContent());
appManager.find("003");
LOGGER.info(appManager.printCacheContent());
UserAccount userAccount6 = new UserAccount("006",
"Yasha",
"She is an only child.");
appManager.save(userAccount6);
LOGGER.info(appManager.printCacheContent());
appManager.find("004");
LOGGER.info(appManager.printCacheContent());
}
/**
* Cache-Aside.
*/
public void useCacheAsideStategy() {
LOGGER.info("# CachingPolicy.ASIDE");
appManager.initCachingPolicy(CachingPolicy.ASIDE);
LOGGER.info(appManager.printCacheContent());
var userAccount3 = new UserAccount("003",
"Adam",
"He likes food.");
var userAccount4 = new UserAccount("004",
"Rita",
"She hates cats.");
var userAccount5 = new UserAccount("005",
"Isaac",
"He is allergic to mustard.");
appManager.save(userAccount3);
appManager.save(userAccount4);
appManager.save(userAccount5);
LOGGER.info(appManager.printCacheContent());
appManager.find("003");
LOGGER.info(appManager.printCacheContent());
appManager.find("004");
LOGGER.info(appManager.printCacheContent());
}
}
|
// VirtualDB (instead of MongoDB) was used in running the JUnit tests
// and the App class to avoid Maven compilation errors. Set flag to
// true to run the tests with MongoDB (provided that MongoDB is
// installed and socket connection is open).
boolean isDbMongo = isDbMongo(args);
if (isDbMongo) {
LOGGER.info("Using the Mongo database engine to run the application.");
} else {
LOGGER.info("Using the 'in Memory' database to run the application.");
}
App app = new App(isDbMongo);
app.useReadAndWriteThroughStrategy();
String splitLine = "==============================================";
LOGGER.info(splitLine);
app.useReadThroughAndWriteAroundStrategy();
LOGGER.info(splitLine);
app.useReadThroughAndWriteBehindStrategy();
LOGGER.info(splitLine);
app.useCacheAsideStategy();
LOGGER.info(splitLine);
| 1,256
| 253
| 1,509
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/caching/src/main/java/com/iluwatar/caching/AppManager.java
|
AppManager
|
save
|
class AppManager {
/**
* Caching Policy.
*/
private CachingPolicy cachingPolicy;
/**
* Database Manager.
*/
private final DbManager dbManager;
/**
* Cache Store.
*/
private final CacheStore cacheStore;
/**
* Constructor.
*
* @param newDbManager database manager
*/
public AppManager(final DbManager newDbManager) {
this.dbManager = newDbManager;
this.cacheStore = new CacheStore(newDbManager);
}
/**
* Developer/Tester is able to choose whether the application should use
* MongoDB as its underlying data storage or a simple Java data structure
* to (temporarily) store the data/objects during runtime.
*/
public void initDb() {
dbManager.connect();
}
/**
* Initialize caching policy.
*
* @param policy is a {@link CachingPolicy}
*/
public void initCachingPolicy(final CachingPolicy policy) {
cachingPolicy = policy;
if (cachingPolicy == CachingPolicy.BEHIND) {
Runtime.getRuntime().addShutdownHook(new Thread(cacheStore::flushCache));
}
cacheStore.clearCache();
}
/**
* Find user account.
*
* @param userId String
* @return {@link UserAccount}
*/
public UserAccount find(final String userId) {
LOGGER.info("Trying to find {} in cache", userId);
if (cachingPolicy == CachingPolicy.THROUGH
|| cachingPolicy == CachingPolicy.AROUND) {
return cacheStore.readThrough(userId);
} else if (cachingPolicy == CachingPolicy.BEHIND) {
return cacheStore.readThroughWithWriteBackPolicy(userId);
} else if (cachingPolicy == CachingPolicy.ASIDE) {
return findAside(userId);
}
return null;
}
/**
* Save user account.
*
* @param userAccount {@link UserAccount}
*/
public void save(final UserAccount userAccount) {<FILL_FUNCTION_BODY>}
/**
* Returns String.
*
* @return String
*/
public String printCacheContent() {
return cacheStore.print();
}
/**
* Cache-Aside save user account helper.
*
* @param userAccount {@link UserAccount}
*/
private void saveAside(final UserAccount userAccount) {
dbManager.updateDb(userAccount);
cacheStore.invalidate(userAccount.getUserId());
}
/**
* Cache-Aside find user account helper.
*
* @param userId String
* @return {@link UserAccount}
*/
private UserAccount findAside(final String userId) {
return Optional.ofNullable(cacheStore.get(userId))
.or(() -> {
Optional<UserAccount> userAccount =
Optional.ofNullable(dbManager.readFromDb(userId));
userAccount.ifPresent(account -> cacheStore.set(userId, account));
return userAccount;
})
.orElse(null);
}
}
|
LOGGER.info("Save record!");
if (cachingPolicy == CachingPolicy.THROUGH) {
cacheStore.writeThrough(userAccount);
} else if (cachingPolicy == CachingPolicy.AROUND) {
cacheStore.writeAround(userAccount);
} else if (cachingPolicy == CachingPolicy.BEHIND) {
cacheStore.writeBehind(userAccount);
} else if (cachingPolicy == CachingPolicy.ASIDE) {
saveAside(userAccount);
}
| 834
| 135
| 969
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/caching/src/main/java/com/iluwatar/caching/CacheStore.java
|
CacheStore
|
writeAround
|
class CacheStore {
/**
* Cache capacity.
*/
private static final int CAPACITY = 3;
/**
* Lru cache see {@link LruCache}.
*/
private LruCache cache;
/**
* DbManager.
*/
private final DbManager dbManager;
/**
* Cache Store.
* @param dataBaseManager {@link DbManager}
*/
public CacheStore(final DbManager dataBaseManager) {
this.dbManager = dataBaseManager;
initCapacity(CAPACITY);
}
/**
* Init cache capacity.
* @param capacity int
*/
public void initCapacity(final int capacity) {
if (cache == null) {
cache = new LruCache(capacity);
} else {
cache.setCapacity(capacity);
}
}
/**
* Get user account using read-through cache.
* @param userId {@link String}
* @return {@link UserAccount}
*/
public UserAccount readThrough(final String userId) {
if (cache.contains(userId)) {
LOGGER.info("# Found in Cache!");
return cache.get(userId);
}
LOGGER.info("# Not found in cache! Go to DB!!");
UserAccount userAccount = dbManager.readFromDb(userId);
cache.set(userId, userAccount);
return userAccount;
}
/**
* Get user account using write-through cache.
* @param userAccount {@link UserAccount}
*/
public void writeThrough(final UserAccount userAccount) {
if (cache.contains(userAccount.getUserId())) {
dbManager.updateDb(userAccount);
} else {
dbManager.writeToDb(userAccount);
}
cache.set(userAccount.getUserId(), userAccount);
}
/**
* Get user account using write-around cache.
* @param userAccount {@link UserAccount}
*/
public void writeAround(final UserAccount userAccount) {<FILL_FUNCTION_BODY>}
/**
* Get user account using read-through cache with write-back policy.
* @param userId {@link String}
* @return {@link UserAccount}
*/
public UserAccount readThroughWithWriteBackPolicy(final String userId) {
if (cache.contains(userId)) {
LOGGER.info("# Found in cache!");
return cache.get(userId);
}
LOGGER.info("# Not found in Cache!");
UserAccount userAccount = dbManager.readFromDb(userId);
if (cache.isFull()) {
LOGGER.info("# Cache is FULL! Writing LRU data to DB...");
UserAccount toBeWrittenToDb = cache.getLruData();
dbManager.upsertDb(toBeWrittenToDb);
}
cache.set(userId, userAccount);
return userAccount;
}
/**
* Set user account.
* @param userAccount {@link UserAccount}
*/
public void writeBehind(final UserAccount userAccount) {
if (cache.isFull() && !cache.contains(userAccount.getUserId())) {
LOGGER.info("# Cache is FULL! Writing LRU data to DB...");
UserAccount toBeWrittenToDb = cache.getLruData();
dbManager.upsertDb(toBeWrittenToDb);
}
cache.set(userAccount.getUserId(), userAccount);
}
/**
* Clears cache.
*/
public void clearCache() {
if (cache != null) {
cache.clear();
}
}
/**
* Writes remaining content in the cache into the DB.
*/
public void flushCache() {
LOGGER.info("# flushCache...");
Optional.ofNullable(cache)
.map(LruCache::getCacheDataInListForm)
.orElse(List.of())
.forEach(dbManager::updateDb);
dbManager.disconnect();
}
/**
* Print user accounts.
* @return {@link String}
*/
public String print() {
return Optional.ofNullable(cache)
.map(LruCache::getCacheDataInListForm)
.orElse(List.of())
.stream()
.map(userAccount -> userAccount.toString() + "\n")
.collect(Collectors.joining("", "\n--CACHE CONTENT--\n", "----"));
}
/**
* Delegate to backing cache store.
* @param userId {@link String}
* @return {@link UserAccount}
*/
public UserAccount get(final String userId) {
return cache.get(userId);
}
/**
* Delegate to backing cache store.
* @param userId {@link String}
* @param userAccount {@link UserAccount}
*/
public void set(final String userId, final UserAccount userAccount) {
cache.set(userId, userAccount);
}
/**
* Delegate to backing cache store.
* @param userId {@link String}
*/
public void invalidate(final String userId) {
cache.invalidate(userId);
}
}
|
if (cache.contains(userAccount.getUserId())) {
dbManager.updateDb(userAccount);
// Cache data has been updated -- remove older
cache.invalidate(userAccount.getUserId());
// version from cache.
} else {
dbManager.writeToDb(userAccount);
}
| 1,355
| 82
| 1,437
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/caching/src/main/java/com/iluwatar/caching/LruCache.java
|
Node
|
setHead
|
class Node {
/**
* user id.
*/
private final String userId;
/**
* User Account.
*/
private UserAccount userAccount;
/**
* previous.
*/
private Node previous;
/**
* next.
*/
private Node next;
/**
* Node definition.
*
* @param id String
* @param account {@link UserAccount}
*/
Node(final String id, final UserAccount account) {
this.userId = id;
this.userAccount = account;
}
}
/**
* Capacity of Cache.
*/
private int capacity;
/**
* Cache {@link HashMap}.
*/
private Map<String, Node> cache = new HashMap<>();
/**
* Head.
*/
private Node head;
/**
* End.
*/
private Node end;
/**
* Constructor.
*
* @param cap Integer.
*/
public LruCache(final int cap) {
this.capacity = cap;
}
/**
* Get user account.
*
* @param userId String
* @return {@link UserAccount}
*/
public UserAccount get(final String userId) {
if (cache.containsKey(userId)) {
var node = cache.get(userId);
remove(node);
setHead(node);
return node.userAccount;
}
return null;
}
/**
* Remove node from linked list.
*
* @param node {@link Node}
*/
public void remove(final Node node) {
if (node.previous != null) {
node.previous.next = node.next;
} else {
head = node.next;
}
if (node.next != null) {
node.next.previous = node.previous;
} else {
end = node.previous;
}
}
/**
* Move node to the front of the list.
*
* @param node {@link Node}
*/
public void setHead(final Node node) {<FILL_FUNCTION_BODY>
|
node.next = head;
node.previous = null;
if (head != null) {
head.previous = node;
}
head = node;
if (end == null) {
end = head;
}
| 568
| 64
| 632
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/caching/src/main/java/com/iluwatar/caching/database/DbManagerFactory.java
|
DbManagerFactory
|
initDb
|
class DbManagerFactory {
/**
* Private constructor.
*/
private DbManagerFactory() {
}
/**
* Init database.
*
* @param isMongo boolean
* @return {@link DbManager}
*/
public static DbManager initDb(final boolean isMongo) {<FILL_FUNCTION_BODY>}
}
|
if (isMongo) {
return new MongoDb();
}
return new VirtualDb();
| 98
| 30
| 128
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/caching/src/main/java/com/iluwatar/caching/database/MongoDb.java
|
MongoDb
|
readFromDb
|
class MongoDb implements DbManager {
private static final String DATABASE_NAME = "admin";
private static final String MONGO_USER = "root";
private static final String MONGO_PASSWORD = "rootpassword";
private MongoClient client;
private MongoDatabase db;
void setDb(MongoDatabase db) {
this.db = db;
}
/**
* Connect to Db. Check th connection
*/
@Override
public void connect() {
MongoCredential mongoCredential = MongoCredential.createCredential(MONGO_USER,
DATABASE_NAME,
MONGO_PASSWORD.toCharArray());
MongoClientOptions options = MongoClientOptions.builder().build();
client = new MongoClient(new ServerAddress(), mongoCredential, options);
db = client.getDatabase(DATABASE_NAME);
}
@Override
public void disconnect() {
client.close();
}
/**
* Read data from DB.
*
* @param userId {@link String}
* @return {@link UserAccount}
*/
@Override
public UserAccount readFromDb(final String userId) {<FILL_FUNCTION_BODY>}
/**
* Write data to DB.
*
* @param userAccount {@link UserAccount}
* @return {@link UserAccount}
*/
@Override
public UserAccount writeToDb(final UserAccount userAccount) {
db.getCollection(USER_ACCOUNT).insertOne(
new Document(USER_ID, userAccount.getUserId())
.append(USER_NAME, userAccount.getUserName())
.append(ADD_INFO, userAccount.getAdditionalInfo())
);
return userAccount;
}
/**
* Update DB.
*
* @param userAccount {@link UserAccount}
* @return {@link UserAccount}
*/
@Override
public UserAccount updateDb(final UserAccount userAccount) {
Document id = new Document(USER_ID, userAccount.getUserId());
Document dataSet = new Document(USER_NAME, userAccount.getUserName())
.append(ADD_INFO, userAccount.getAdditionalInfo());
db.getCollection(CachingConstants.USER_ACCOUNT)
.updateOne(id, new Document("$set", dataSet));
return userAccount;
}
/**
* Update data if exists.
*
* @param userAccount {@link UserAccount}
* @return {@link UserAccount}
*/
@Override
public UserAccount upsertDb(final UserAccount userAccount) {
String userId = userAccount.getUserId();
String userName = userAccount.getUserName();
String additionalInfo = userAccount.getAdditionalInfo();
db.getCollection(CachingConstants.USER_ACCOUNT).updateOne(
new Document(USER_ID, userId),
new Document("$set",
new Document(USER_ID, userId)
.append(USER_NAME, userName)
.append(ADD_INFO, additionalInfo)
),
new UpdateOptions().upsert(true)
);
return userAccount;
}
}
|
var iterable = db
.getCollection(CachingConstants.USER_ACCOUNT)
.find(new Document(USER_ID, userId));
if (iterable.first() == null) {
return null;
}
Document doc = iterable.first();
if (doc != null) {
String userName = doc.getString(USER_NAME);
String appInfo = doc.getString(ADD_INFO);
return new UserAccount(userId, userName, appInfo);
} else {
return null;
}
| 810
| 138
| 948
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/callback/src/main/java/com/iluwatar/callback/App.java
|
App
|
main
|
class App {
private App() {
}
/**
* Program entry point.
*/
public static void main(final String[] args) {<FILL_FUNCTION_BODY>}
}
|
var task = new SimpleTask();
task.executeWith(() -> LOGGER.info("I'm done now."));
| 55
| 33
| 88
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/callback/src/main/java/com/iluwatar/callback/SimpleTask.java
|
SimpleTask
|
execute
|
class SimpleTask extends Task {
@Override
public void execute() {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Perform some important activity and after call the callback method.");
| 33
| 22
| 55
|
<methods>public non-sealed void <init>() ,public abstract void execute() <variables>
|
iluwatar_java-design-patterns
|
java-design-patterns/chain-of-responsibility/src/main/java/com/iluwatar/chain/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var king = new OrcKing();
king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle"));
king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner"));
king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax"));
| 56
| 90
| 146
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcKing.java
|
OrcKing
|
makeRequest
|
class OrcKing {
private List<RequestHandler> handlers;
public OrcKing() {
buildChain();
}
private void buildChain() {
handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier());
}
/**
* Handle request by the chain.
*/
public void makeRequest(Request req) {<FILL_FUNCTION_BODY>}
}
|
handlers
.stream()
.sorted(Comparator.comparing(RequestHandler::getPriority))
.filter(handler -> handler.canHandleRequest(req))
.findFirst()
.ifPresent(handler -> handler.handle(req));
| 119
| 68
| 187
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var serverStartTime = System.nanoTime();
var delayedService = new DelayedRemoteService(serverStartTime, 5);
var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 2,
2000 * 1000 * 1000);
var quickService = new QuickRemoteService();
var quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, 2,
2000 * 1000 * 1000);
//Create an object of monitoring service which makes both local and remote calls
var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,
quickServiceCircuitBreaker);
//Fetch response from local resource
LOGGER.info(monitoringService.localResourceResponse());
//Fetch response from delayed service 2 times, to meet the failure threshold
LOGGER.info(monitoringService.delayedServiceResponse());
LOGGER.info(monitoringService.delayedServiceResponse());
//Fetch current state of delayed service circuit breaker after crossing failure threshold limit
//which is OPEN now
LOGGER.info(delayedServiceCircuitBreaker.getState());
//Meanwhile, the delayed service is down, fetch response from the healthy quick service
LOGGER.info(monitoringService.quickServiceResponse());
LOGGER.info(quickServiceCircuitBreaker.getState());
//Wait for the delayed service to become responsive
try {
LOGGER.info("Waiting for delayed service to become responsive");
Thread.sleep(5000);
} catch (InterruptedException e) {
LOGGER.error("An error occurred: ", e);
}
//Check the state of delayed circuit breaker, should be HALF_OPEN
LOGGER.info(delayedServiceCircuitBreaker.getState());
//Fetch response from delayed service, which should be healthy by now
LOGGER.info(monitoringService.delayedServiceResponse());
//As successful response is fetched, it should be CLOSED again.
LOGGER.info(delayedServiceCircuitBreaker.getState());
| 56
| 541
| 597
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java
|
DefaultCircuitBreaker
|
attemptRequest
|
class DefaultCircuitBreaker implements CircuitBreaker {
private final long timeout;
private final long retryTimePeriod;
private final RemoteService service;
long lastFailureTime;
private String lastFailureResponse;
int failureCount;
private final int failureThreshold;
private State state;
// Future time offset, in nanoseconds
private final long futureTime = 1_000_000_000_000L;
/**
* Constructor to create an instance of Circuit Breaker.
*
* @param timeout Timeout for the API request. Not necessary for this simple example
* @param failureThreshold Number of failures we receive from the depended on service before
* changing state to 'OPEN'
* @param retryTimePeriod Time, in nanoseconds, period after which a new request is made to
* remote service for status check.
*/
DefaultCircuitBreaker(RemoteService serviceToCall, long timeout, int failureThreshold,
long retryTimePeriod) {
this.service = serviceToCall;
// We start in a closed state hoping that everything is fine
this.state = State.CLOSED;
this.failureThreshold = failureThreshold;
// Timeout for the API request.
// Used to break the calls made to remote resource if it exceeds the limit
this.timeout = timeout;
this.retryTimePeriod = retryTimePeriod;
//An absurd amount of time in future which basically indicates the last failure never happened
this.lastFailureTime = System.nanoTime() + futureTime;
this.failureCount = 0;
}
// Reset everything to defaults
@Override
public void recordSuccess() {
this.failureCount = 0;
this.lastFailureTime = System.nanoTime() + futureTime;
this.state = State.CLOSED;
}
@Override
public void recordFailure(String response) {
failureCount = failureCount + 1;
this.lastFailureTime = System.nanoTime();
// Cache the failure response for returning on open state
this.lastFailureResponse = response;
}
// Evaluate the current state based on failureThreshold, failureCount and lastFailureTime.
protected void evaluateState() {
if (failureCount >= failureThreshold) { //Then something is wrong with remote service
if ((System.nanoTime() - lastFailureTime) > retryTimePeriod) {
//We have waited long enough and should try checking if service is up
state = State.HALF_OPEN;
} else {
//Service would still probably be down
state = State.OPEN;
}
} else {
//Everything is working fine
state = State.CLOSED;
}
}
@Override
public String getState() {
evaluateState();
return state.name();
}
/**
* Break the circuit beforehand if it is known service is down Or connect the circuit manually if
* service comes online before expected.
*
* @param state State at which circuit is in
*/
@Override
public void setState(State state) {
this.state = state;
switch (state) {
case OPEN -> {
this.failureCount = failureThreshold;
this.lastFailureTime = System.nanoTime();
}
case HALF_OPEN -> {
this.failureCount = failureThreshold;
this.lastFailureTime = System.nanoTime() - retryTimePeriod;
}
default -> this.failureCount = 0;
}
}
/**
* Executes service call.
*
* @return Value from the remote resource, stale response or a custom exception
*/
@Override
public String attemptRequest() throws RemoteServiceException {<FILL_FUNCTION_BODY>}
}
|
evaluateState();
if (state == State.OPEN) {
// return cached response if the circuit is in OPEN state
return this.lastFailureResponse;
} else {
// Make the API request if the circuit is not OPEN
try {
//In a real application, this would be run in a thread and the timeout
//parameter of the circuit breaker would be utilized to know if service
//is working. Here, we simulate that based on server response itself
var response = service.call();
// Yay!! the API responded fine. Let's reset everything.
recordSuccess();
return response;
} catch (RemoteServiceException ex) {
recordFailure(ex.getMessage());
throw ex;
}
}
| 967
| 183
| 1,150
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedRemoteService.java
|
DelayedRemoteService
|
call
|
class DelayedRemoteService implements RemoteService {
private final long serverStartTime;
private final int delay;
/**
* Constructor to create an instance of DelayedService, which is down for first few seconds.
*
* @param delay the delay after which service would behave properly, in seconds
*/
public DelayedRemoteService(long serverStartTime, int delay) {
this.serverStartTime = serverStartTime;
this.delay = delay;
}
public DelayedRemoteService() {
this.serverStartTime = System.nanoTime();
this.delay = 20;
}
/**
* Responds based on delay, current time and server start time if the service is down / working.
*
* @return The state of the service
*/
@Override
public String call() throws RemoteServiceException {<FILL_FUNCTION_BODY>}
}
|
var currentTime = System.nanoTime();
//Since currentTime and serverStartTime are both in nanoseconds, we convert it to
//seconds by diving by 10e9 and ensure floating point division by multiplying it
//with 1.0 first. We then check if it is greater or less than specified delay and then
//send the reply
if ((currentTime - serverStartTime) * 1.0 / (1000 * 1000 * 1000) < delay) {
//Can use Thread.sleep() here to block and simulate a hung server
throw new RemoteServiceException("Delayed service is down");
}
return "Delayed service is working";
| 229
| 172
| 401
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java
|
MonitoringService
|
delayedServiceResponse
|
class MonitoringService {
private final CircuitBreaker delayedService;
private final CircuitBreaker quickService;
public MonitoringService(CircuitBreaker delayedService, CircuitBreaker quickService) {
this.delayedService = delayedService;
this.quickService = quickService;
}
//Assumption: Local service won't fail, no need to wrap it in a circuit breaker logic
public String localResourceResponse() {
return "Local Service is working";
}
/**
* Fetch response from the delayed service (with some simulated startup time).
*
* @return response string
*/
public String delayedServiceResponse() {<FILL_FUNCTION_BODY>}
/**
* Fetches response from a healthy service without any failure.
*
* @return response string
*/
public String quickServiceResponse() {
try {
return this.quickService.attemptRequest();
} catch (RemoteServiceException e) {
return e.getMessage();
}
}
}
|
try {
return this.delayedService.attemptRequest();
} catch (RemoteServiceException e) {
return e.getMessage();
}
| 258
| 41
| 299
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/client-session/src/main/java/com/iluwatar/client/session/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args Command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var server = new Server("localhost", 8080);
var session1 = server.getSession("Session1");
var session2 = server.getSession("Session2");
var request1 = new Request("Data1", session1);
var request2 = new Request("Data2", session2);
server.process(request1);
server.process(request2);
| 56
| 95
| 151
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/client-session/src/main/java/com/iluwatar/client/session/Server.java
|
Server
|
process
|
class Server {
private String host;
private int port;
/**
* Creates a new session.
*
* @param name name of the client
*
* @return Session Object
*/
public Session getSession(String name) {
return new Session(UUID.randomUUID().toString(), name);
}
/**
* Processes a request based on the session.
*
* @param request Request object with data and Session
*/
public void process(Request request) {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Processing Request with client: " + request.getSession().getClientName() + " data: " + request.getData());
| 145
| 38
| 183
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/App.java
|
App
|
main
|
class App {
static PrinterQueue printerQueue = PrinterQueue.getInstance();
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
/**
* Adds A4 document jobs to the collecting parameter according to some policy that can be whatever the client
* (the print center) wants.
*
* @param printerItemsCollection the collecting parameter
*/
public static void addValidA4Papers(Queue<PrinterItem> printerItemsCollection) {
/*
Iterate through the printer queue, and add A4 papers according to the correct policy to the collecting parameter,
which is 'printerItemsCollection' in this case.
*/
for (PrinterItem nextItem : printerQueue.getPrinterQueue()) {
if (nextItem.paperSize.equals(PaperSizes.A4)) {
var isColouredAndSingleSided = nextItem.isColour && !nextItem.isDoubleSided;
if (isColouredAndSingleSided || !nextItem.isColour) {
printerItemsCollection.add(nextItem);
}
}
}
}
/**
* Adds A3 document jobs to the collecting parameter according to some policy that can be whatever the client
* (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate
* the wants of the client.
*
* @param printerItemsCollection the collecting parameter
*/
public static void addValidA3Papers(Queue<PrinterItem> printerItemsCollection) {
for (PrinterItem nextItem : printerQueue.getPrinterQueue()) {
if (nextItem.paperSize.equals(PaperSizes.A3)) {
// Encoding the policy into a Boolean: the A3 paper cannot be coloured and double-sided at the same time
var isNotColouredAndSingleSided = !nextItem.isColour && !nextItem.isDoubleSided;
if (isNotColouredAndSingleSided) {
printerItemsCollection.add(nextItem);
}
}
}
}
/**
* Adds A2 document jobs to the collecting parameter according to some policy that can be whatever the client
* (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate
* the wants of the client.
*
* @param printerItemsCollection the collecting parameter
*/
public static void addValidA2Papers(Queue<PrinterItem> printerItemsCollection) {
for (PrinterItem nextItem : printerQueue.getPrinterQueue()) {
if (nextItem.paperSize.equals(PaperSizes.A2)) {
// Encoding the policy into a Boolean: the A2 paper must be single page, single-sided, and non-coloured.
var isNotColouredSingleSidedAndOnePage = nextItem.pageCount == 1 && !nextItem.isDoubleSided
&& !nextItem.isColour;
if (isNotColouredSingleSidedAndOnePage) {
printerItemsCollection.add(nextItem);
}
}
}
}
}
|
/*
Initialising the printer queue with jobs
*/
printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A4, 5, false, false));
printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A3, 2, false, false));
printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A2, 5, false, false));
/*
This variable is the collecting parameter, and will store the policy abiding print jobs.
*/
var result = new LinkedList<PrinterItem>();
/*
Adding A4, A3, and A2 papers that obey the policy
*/
addValidA4Papers(result);
addValidA3Papers(result);
addValidA2Papers(result);
| 806
| 206
| 1,012
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterQueue.java
|
PrinterQueue
|
getInstance
|
class PrinterQueue {
static PrinterQueue currentInstance = null;
private final Queue<PrinterItem> printerItemQueue;
/**
* This class is a singleton. The getInstance method will ensure that only one instance exists at a time.
*/
public static PrinterQueue getInstance() {<FILL_FUNCTION_BODY>}
/**
* Empty the printer queue.
*/
public void emptyQueue() {
currentInstance.getPrinterQueue().clear();
}
/**
* Private constructor prevents instantiation, unless using the getInstance() method.
*/
private PrinterQueue() {
printerItemQueue = new LinkedList<>();
}
public Queue<PrinterItem> getPrinterQueue() {
return currentInstance.printerItemQueue;
}
/**
* Adds a single print job to the queue.
*
* @param printerItem The printing job to be added to the queue
*/
public void addPrinterItem(PrinterItem printerItem) {
currentInstance.getPrinterQueue().add(printerItem);
}
}
|
if (Objects.isNull(currentInstance)) {
currentInstance = new PrinterQueue();
}
return currentInstance;
| 281
| 35
| 316
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var cars = CarFactory.createCars();
var modelsImperative = ImperativeProgramming.getModelsAfter2000(cars);
LOGGER.info(modelsImperative.toString());
var modelsFunctional = FunctionalProgramming.getModelsAfter2000(cars);
LOGGER.info(modelsFunctional.toString());
var groupingByCategoryImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars);
LOGGER.info(groupingByCategoryImperative.toString());
var groupingByCategoryFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars);
LOGGER.info(groupingByCategoryFunctional.toString());
var john = new Person(cars);
var sedansOwnedImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(List.of(john));
LOGGER.info(sedansOwnedImperative.toString());
var sedansOwnedFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john));
LOGGER.info(sedansOwnedFunctional.toString());
| 56
| 300
| 356
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java
|
CarFactory
|
createCars
|
class CarFactory {
private CarFactory() {
}
/**
* Factory method to create a {@link List} of {@link Car} instances.
*
* @return {@link List} of {@link Car}
*/
public static List<Car> createCars() {<FILL_FUNCTION_BODY>}
}
|
return List.of(new Car("Jeep", "Wrangler", 2011, Category.JEEP),
new Car("Jeep", "Comanche", 1990, Category.JEEP),
new Car("Dodge", "Avenger", 2010, Category.SEDAN),
new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE),
new Car("Ford", "Focus", 2012, Category.SEDAN),
new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE));
| 85
| 161
| 246
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java
|
ImperativeProgramming
|
getSedanCarsOwnedSortedByDate
|
class ImperativeProgramming {
private ImperativeProgramming() {
}
/**
* Method to return the car models built after year 2000 using for loops.
*
* @param cars {@link List} of {@link Car} to iterate over
* @return {@link List} of {@link String} of car models built after year 2000
*/
public static List<String> getModelsAfter2000(List<Car> cars) {
List<Car> carsSortedByYear = new ArrayList<>();
for (Car car : cars) {
if (car.year() > 2000) {
carsSortedByYear.add(car);
}
}
Collections.sort(carsSortedByYear, new Comparator<Car>() {
@Override
public int compare(Car car1, Car car2) {
return car1.year() - car2.year();
}
});
List<String> models = new ArrayList<>();
for (Car car : carsSortedByYear) {
models.add(car.model());
}
return models;
}
/**
* Method to group cars by category using for loops.
*
* @param cars {@link List} of {@link Car} to be used for grouping
* @return {@link Map} with category as key and cars belonging to that category as value
*/
public static Map<Category, List<Car>> getGroupingOfCarsByCategory(List<Car> cars) {
Map<Category, List<Car>> groupingByCategory = new HashMap<>();
for (Car car : cars) {
if (groupingByCategory.containsKey(car.category())) {
groupingByCategory.get(car.category()).add(car);
} else {
List<Car> categoryCars = new ArrayList<>();
categoryCars.add(car);
groupingByCategory.put(car.category(), categoryCars);
}
}
return groupingByCategory;
}
/**
* Method to get all Sedan cars belonging to a group of persons sorted by year of manufacture
* using for loops.
*
* @param persons {@link List} of {@link Person} to be used
* @return {@link List} of {@link Car} to belonging to the group
*/
public static List<Car> getSedanCarsOwnedSortedByDate(List<Person> persons) {<FILL_FUNCTION_BODY>}
}
|
List<Car> cars = new ArrayList<>();
for (Person person : persons) {
cars.addAll(person.cars());
}
List<Car> sedanCars = new ArrayList<>();
for (Car car : cars) {
if (Category.SEDAN.equals(car.category())) {
sedanCars.add(car);
}
}
sedanCars.sort(new Comparator<Car>() {
@Override
public int compare(Car o1, Car o2) {
return o1.year() - o2.year();
}
});
return sedanCars;
| 627
| 166
| 793
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/combinator/src/main/java/com/iluwatar/combinator/CombinatorApp.java
|
CombinatorApp
|
main
|
class CombinatorApp {
private static final String TEXT = """
It was many and many a year ago,
In a kingdom by the sea,
That a maiden there lived whom you may know
By the name of ANNABEL LEE;
And this maiden she lived with no other thought
Than to love and be loved by me.
I was a child and she was a child,
In this kingdom by the sea;
But we loved with a love that was more than love-
I and my Annabel Lee;
With a love that the winged seraphs of heaven
Coveted her and me.""";
/**
* main.
* @param args args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
private static String text() {
return TEXT;
}
}
|
var queriesOr = new String[]{"many", "Annabel"};
var finder = Finders.expandedFinder(queriesOr);
var res = finder.find(text());
LOGGER.info("the result of expanded(or) query[{}] is {}", queriesOr, res);
var queriesAnd = new String[]{"Annabel", "my"};
finder = Finders.specializedFinder(queriesAnd);
res = finder.find(text());
LOGGER.info("the result of specialized(and) query[{}] is {}", queriesAnd, res);
finder = Finders.advancedFinder("it was", "kingdom", "sea");
res = finder.find(text());
LOGGER.info("the result of advanced query is {}", res);
res = Finders.filteredFinder(" was ", "many", "child").find(text());
LOGGER.info("the result of filtered query is {}", res);
| 221
| 243
| 464
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/combinator/src/main/java/com/iluwatar/combinator/Finders.java
|
Finders
|
filteredFinder
|
class Finders {
private Finders() {
}
/**
* Finder to find a complex query.
* @param query to find
* @param orQuery alternative to find
* @param notQuery exclude from search
* @return new finder
*/
public static Finder advancedFinder(String query, String orQuery, String notQuery) {
return
Finder.contains(query)
.or(Finder.contains(orQuery))
.not(Finder.contains(notQuery));
}
/**
* Filtered finder looking a query with excluded queries as well.
* @param query to find
* @param excludeQueries to exclude
* @return new finder
*/
public static Finder filteredFinder(String query, String... excludeQueries) {<FILL_FUNCTION_BODY>}
/**
* Specialized query. Every next query is looked in previous result.
* @param queries array with queries
* @return new finder
*/
public static Finder specializedFinder(String... queries) {
var finder = identMult();
for (String query : queries) {
finder = finder.and(Finder.contains(query));
}
return finder;
}
/**
* Expanded query. Looking for alternatives.
* @param queries array with queries.
* @return new finder
*/
public static Finder expandedFinder(String... queries) {
var finder = identSum();
for (String query : queries) {
finder = finder.or(Finder.contains(query));
}
return finder;
}
private static Finder identMult() {
return txt -> Stream.of(txt.split("\n")).collect(Collectors.toList());
}
private static Finder identSum() {
return txt -> new ArrayList<>();
}
}
|
var finder = Finder.contains(query);
for (String q : excludeQueries) {
finder = finder.not(Finder.contains(q));
}
return finder;
| 475
| 55
| 530
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/command/src/main/java/com/iluwatar/command/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var wizard = new Wizard();
var goblin = new Goblin();
goblin.printStatus();
wizard.castSpell(goblin::changeSize);
goblin.printStatus();
wizard.castSpell(goblin::changeVisibility);
goblin.printStatus();
wizard.undoLastSpell();
goblin.printStatus();
wizard.undoLastSpell();
goblin.printStatus();
wizard.redoLastSpell();
goblin.printStatus();
wizard.redoLastSpell();
goblin.printStatus();
| 56
| 170
| 226
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/command/src/main/java/com/iluwatar/command/Target.java
|
Target
|
changeVisibility
|
class Target {
private Size size;
private Visibility visibility;
/**
* Print status.
*/
public void printStatus() {
LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility());
}
/**
* Changes the size of the target.
*/
public void changeSize() {
var oldSize = getSize() == Size.NORMAL ? Size.SMALL : Size.NORMAL;
setSize(oldSize);
}
/**
* Changes the visibility of the target.
*/
public void changeVisibility() {<FILL_FUNCTION_BODY>}
}
|
var visible = getVisibility() == Visibility.INVISIBLE
? Visibility.VISIBLE : Visibility.INVISIBLE;
setVisibility(visible);
| 203
| 53
| 256
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/command/src/main/java/com/iluwatar/command/Wizard.java
|
Wizard
|
undoLastSpell
|
class Wizard {
private final Deque<Runnable> undoStack = new LinkedList<>();
private final Deque<Runnable> redoStack = new LinkedList<>();
/**
* Cast spell.
*/
public void castSpell(Runnable runnable) {
runnable.run();
undoStack.offerLast(runnable);
}
/**
* Undo last spell.
*/
public void undoLastSpell() {<FILL_FUNCTION_BODY>}
/**
* Redo last spell.
*/
public void redoLastSpell() {
if (!redoStack.isEmpty()) {
var previousSpell = redoStack.pollLast();
undoStack.offerLast(previousSpell);
previousSpell.run();
}
}
@Override
public String toString() {
return "Wizard";
}
}
|
if (!undoStack.isEmpty()) {
var previousSpell = undoStack.pollLast();
redoStack.offerLast(previousSpell);
previousSpell.run();
}
| 245
| 53
| 298
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/AppEmployeeDbFailCases.java
|
AppEmployeeDbFailCases
|
employeeDatabaseUnavailableCase
|
class AppEmployeeDbFailCases {
private final int numOfRetries = 3;
private final long retryDuration = 30000;
private final long queueTime = 240000; //4 mins
private final long queueTaskTime = 60000; //1 min
private final long paymentTime = 120000; //2 mins
private final long messageTime = 150000; //2.5 mins
private final long employeeTime = 240000; //4 mins
void employeeDatabaseUnavailableCase() throws Exception {<FILL_FUNCTION_BODY>}
void employeeDbSuccessCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) throws Exception {
var aefc = new AppEmployeeDbFailCases();
//aefc.employeeDatabaseUnavailableCase();
aefc.employeeDbSuccessCase();
}
}
|
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
| 442
| 288
| 730
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/AppMessagingFailCases.java
|
AppMessagingFailCases
|
messagingDatabaseUnavailableCasePaymentError
|
class AppMessagingFailCases {
private final int numOfRetries = 3;
private final long retryDuration = 30000;
private final long queueTime = 240000; //4 mins
private final long queueTaskTime = 60000; //1 min
private final long paymentTime = 120000; //2 mins
private final long messageTime = 150000; //2.5 mins
private final long employeeTime = 240000; //4 mins
void messagingDatabaseUnavailableCasePaymentSuccess() throws Exception {
//rest is successful
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void messagingDatabaseUnavailableCasePaymentError() throws Exception {<FILL_FUNCTION_BODY>}
void messagingDatabaseUnavailableCasePaymentFailure() throws Exception {
//rest is successful
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c =
new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, queueTime, queueTaskTime,
paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void messagingSuccessCase() throws Exception {
//done here
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) throws Exception {
var amfc = new AppMessagingFailCases();
//amfc.messagingDatabaseUnavailableCasePaymentSuccess();
//amfc.messagingDatabaseUnavailableCasePaymentError();
//amfc.messagingDatabaseUnavailableCasePaymentFailure();
amfc.messagingSuccessCase();
}
}
|
//rest is successful
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
| 1,062
| 322
| 1,384
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/AppPaymentFailCases.java
|
AppPaymentFailCases
|
paymentNotPossibleCase
|
class AppPaymentFailCases {
private final int numOfRetries = 3;
private final long retryDuration = 30000;
private final long queueTime = 240000; //4 mins
private final long queueTaskTime = 60000; //1 min
private final long paymentTime = 120000; //2 mins
private final long messageTime = 150000; //2.5 mins
private final long employeeTime = 240000; //4 mins
void paymentNotPossibleCase() throws Exception {<FILL_FUNCTION_BODY>}
void paymentDatabaseUnavailableCase() throws Exception {
//rest is successful
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void paymentSuccessCase() throws Exception {
//goes to message after 2 retries maybe - rest is successful for now
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms =
new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase(new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) throws Exception {
var apfc = new AppPaymentFailCases();
//apfc.paymentNotPossibleCase();
//apfc.paymentDatabaseUnavailableCase();
apfc.paymentSuccessCase();
}
}
|
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new PaymentDetailsErrorException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase(new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
| 696
| 189
| 885
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/AppQueueFailCases.java
|
AppQueueFailCases
|
queueMessageTaskDatabaseUnavailableCase
|
class AppQueueFailCases {
private final int numOfRetries = 3;
private final long retryDuration = 30000;
private final long queueTime = 240000; //4 mins
private final long queueTaskTime = 60000; //1 min
private final long paymentTime = 120000; //2 mins
private final long messageTime = 150000; //2.5 mins
private final long employeeTime = 240000; //4 mins
void queuePaymentTaskDatabaseUnavailableCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void queueMessageTaskDatabaseUnavailableCase() throws Exception {<FILL_FUNCTION_BODY>}
void queueEmployeeDbTaskDatabaseUnavailableCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void queueSuccessCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms =
new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) throws Exception {
var aqfc = new AppQueueFailCases();
//aqfc.queuePaymentTaskDatabaseUnavailableCase();
//aqfc.queueMessageTaskDatabaseUnavailableCase();
//aqfc.queueEmployeeDbTaskDatabaseUnavailableCase();
aqfc.queueSuccessCase();
}
}
|
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
| 1,138
| 246
| 1,384
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/AppShippingFailCases.java
|
AppShippingFailCases
|
itemUnavailableCase
|
class AppShippingFailCases {
private final int numOfRetries = 3;
private final long retryDuration = 30000;
private final long queueTime = 240000; //4 mins
private final long queueTaskTime = 60000; //1 min
private final long paymentTime = 120000; //2 mins
private final long messageTime = 150000; //2.5 mins
private final long employeeTime = 240000; //4 mins
void itemUnavailableCase() throws Exception {<FILL_FUNCTION_BODY>}
void shippingNotPossibleCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase(), new ShippingNotPossibleException());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void shippingDatabaseUnavailableCase() throws Exception {
//rest is successful
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void shippingSuccessCase() throws Exception {
//goes to payment after 2 retries maybe - rest is successful for now
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) throws Exception {
var asfc = new AppShippingFailCases();
//asfc.itemUnavailableCase();
//asfc.shippingNotPossibleCase();
//asfc.shippingDatabaseUnavailableCase();
asfc.shippingSuccessCase();
}
}
|
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
| 888
| 168
| 1,056
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/Order.java
|
Order
|
createUniqueId
|
class Order { //can store all transactions ids also
enum PaymentStatus {
NOT_DONE,
TRYING,
DONE
}
enum MessageSent {
NONE_SENT,
PAYMENT_FAIL,
PAYMENT_TRYING,
PAYMENT_SUCCESSFUL
}
final User user;
final String item;
public final String id;
final float price;
final long createdTime;
private static final SecureRandom RANDOM = new SecureRandom();
private static final String ALL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final Map<String, Boolean> USED_IDS = new HashMap<>();
PaymentStatus paid;
MessageSent messageSent; //to avoid sending error msg on page and text more than once
boolean addedToEmployeeHandle; //to avoid creating more to enqueue
Order(User user, String item, float price) {
this.createdTime = System.currentTimeMillis();
this.user = user;
this.item = item;
this.price = price;
String id = createUniqueId();
if (USED_IDS.get(id) != null) {
while (USED_IDS.get(id)) {
id = createUniqueId();
}
}
this.id = id;
USED_IDS.put(this.id, true);
this.paid = PaymentStatus.TRYING;
this.messageSent = MessageSent.NONE_SENT;
this.addedToEmployeeHandle = false;
}
private String createUniqueId() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder random = new StringBuilder();
while (random.length() < 12) { // length of the random string.
int index = (int) (RANDOM.nextFloat() * ALL_CHARS.length());
random.append(ALL_CHARS.charAt(index));
}
return random.toString();
| 447
| 83
| 530
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/Retry.java
|
Retry
|
perform
|
class Retry<T> {
/**
* Operation Interface will define method to be implemented.
*/
public interface Operation {
void operation(List<Exception> list) throws Exception;
}
/**
* HandleErrorIssue defines how to handle errors.
*
* @param <T> is the type of object to be passed into the method as parameter.
*/
public interface HandleErrorIssue<T> {
void handleIssue(T obj, Exception e);
}
private static final SecureRandom RANDOM = new SecureRandom();
private final Operation op;
private final HandleErrorIssue<T> handleError;
private final int maxAttempts;
private final long maxDelay;
private final AtomicInteger attempts;
private final Predicate<Exception> test;
private final List<Exception> errors;
Retry(Operation op, HandleErrorIssue<T> handleError, int maxAttempts,
long maxDelay, Predicate<Exception>... ignoreTests) {
this.op = op;
this.handleError = handleError;
this.maxAttempts = maxAttempts;
this.maxDelay = maxDelay;
this.attempts = new AtomicInteger();
this.test = Arrays.stream(ignoreTests).reduce(Predicate::or).orElse(e -> false);
this.errors = new ArrayList<>();
}
/**
* Performing the operation with retries.
*
* @param list is the exception list
* @param obj is the parameter to be passed into handleIsuue method
*/
public void perform(List<Exception> list, T obj) {<FILL_FUNCTION_BODY>}
}
|
do {
try {
op.operation(list);
return;
} catch (Exception e) {
this.errors.add(e);
if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) {
this.handleError.handleIssue(obj, e);
return; //return here... don't go further
}
try {
long testDelay =
(long) Math.pow(2, this.attempts.intValue()) * 1000 + RANDOM.nextInt(1000);
long delay = Math.min(testDelay, this.maxDelay);
Thread.sleep(delay);
} catch (InterruptedException f) {
//ignore
}
}
} while (true);
| 435
| 208
| 643
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/Service.java
|
Service
|
generateId
|
class Service {
protected final Database database;
public ArrayList<Exception> exceptionsList;
private static final SecureRandom RANDOM = new SecureRandom();
private static final String ALL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final Hashtable<String, Boolean> USED_IDS = new Hashtable<>();
protected Service(Database db, Exception... exc) {
this.database = db;
this.exceptionsList = new ArrayList<>(List.of(exc));
}
public abstract String receiveRequest(Object... parameters) throws DatabaseUnavailableException;
protected abstract String updateDb(Object... parameters) throws DatabaseUnavailableException;
protected String generateId() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder random = new StringBuilder();
while (random.length() < 12) { // length of the random string.
int index = (int) (RANDOM.nextFloat() * ALL_CHARS.length());
random.append(ALL_CHARS.charAt(index));
}
String id = random.toString();
if (USED_IDS.get(id) != null) {
while (USED_IDS.get(id)) {
id = generateId();
}
}
return id;
| 207
| 135
| 342
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java
|
EmployeeHandle
|
updateDb
|
class EmployeeHandle extends Service {
public EmployeeHandle(EmployeeDatabase db, Exception... exc) {
super(db, exc);
}
public String receiveRequest(Object... parameters) throws DatabaseUnavailableException {
return updateDb(parameters[0]);
}
protected String updateDb(Object... parameters) throws DatabaseUnavailableException {<FILL_FUNCTION_BODY>}
}
|
var o = (Order) parameters[0];
if (database.get(o.id) == null) {
database.add(o);
return o.id; //true rcvd - change addedToEmployeeHandle to true else don't do anything
}
return null;
| 102
| 75
| 177
|
<methods>public transient abstract java.lang.String receiveRequest(java.lang.Object[]) throws com.iluwatar.commander.exceptions.DatabaseUnavailableException<variables>private static final java.lang.String ALL_CHARS,private static final java.security.SecureRandom RANDOM,private static final Hashtable<java.lang.String,java.lang.Boolean> USED_IDS,protected final non-sealed Database#RAW database,public ArrayList<java.lang.Exception> exceptionsList
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java
|
MessagingService
|
sendMessage
|
class MessagingService extends Service {
enum MessageToSend {
PAYMENT_FAIL,
PAYMENT_TRYING,
PAYMENT_SUCCESSFUL
}
record MessageRequest(String reqId, MessageToSend msg) {}
public MessagingService(MessagingDatabase db, Exception... exc) {
super(db, exc);
}
/**
* Public method which will receive request from {@link com.iluwatar.commander.Commander}.
*/
public String receiveRequest(Object... parameters) throws DatabaseUnavailableException {
var messageToSend = (int) parameters[0];
var id = generateId();
MessageToSend msg;
if (messageToSend == 0) {
msg = MessageToSend.PAYMENT_FAIL;
} else if (messageToSend == 1) {
msg = MessageToSend.PAYMENT_TRYING;
} else { //messageToSend == 2
msg = MessageToSend.PAYMENT_SUCCESSFUL;
}
var req = new MessageRequest(id, msg);
return updateDb(req);
}
protected String updateDb(Object... parameters) throws DatabaseUnavailableException {
var req = (MessageRequest) parameters[0];
if (this.database.get(req.reqId) == null) { //idempotence, in case db fails here
database.add(req); //if successful:
LOGGER.info(sendMessage(req.msg));
return req.reqId;
}
return null;
}
String sendMessage(MessageToSend m) {<FILL_FUNCTION_BODY>}
}
|
if (m.equals(MessageToSend.PAYMENT_SUCCESSFUL)) {
return "Msg: Your order has been placed and paid for successfully!"
+ " Thank you for shopping with us!";
} else if (m.equals(MessageToSend.PAYMENT_TRYING)) {
return "Msg: There was an error in your payment process,"
+ " we are working on it and will return back to you shortly."
+ " Meanwhile, your order has been placed and will be shipped.";
} else {
return "Msg: There was an error in your payment process."
+ " Your order is placed and has been converted to COD."
+ " Please reach us on CUSTOMER-CARE-NUBER in case of any queries."
+ " Thank you for shopping with us!";
}
| 416
| 201
| 617
|
<methods>public transient abstract java.lang.String receiveRequest(java.lang.Object[]) throws com.iluwatar.commander.exceptions.DatabaseUnavailableException<variables>private static final java.lang.String ALL_CHARS,private static final java.security.SecureRandom RANDOM,private static final Hashtable<java.lang.String,java.lang.Boolean> USED_IDS,protected final non-sealed Database#RAW database,public ArrayList<java.lang.Exception> exceptionsList
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java
|
PaymentRequest
|
receiveRequest
|
class PaymentRequest {
final String transactionId;
final float payment;
boolean paid;
}
public PaymentService(PaymentDatabase db, Exception... exc) {
super(db, exc);
}
/**
* Public method which will receive request from {@link com.iluwatar.commander.Commander}.
*/
public String receiveRequest(Object... parameters) throws DatabaseUnavailableException {<FILL_FUNCTION_BODY>
|
//it could also be sending an userid, payment details here or something, not added here
var id = generateId();
var req = new PaymentRequest(id, (float) parameters[0]);
return updateDb(req);
| 117
| 59
| 176
|
<methods>public transient abstract java.lang.String receiveRequest(java.lang.Object[]) throws com.iluwatar.commander.exceptions.DatabaseUnavailableException<variables>private static final java.lang.String ALL_CHARS,private static final java.security.SecureRandom RANDOM,private static final Hashtable<java.lang.String,java.lang.Boolean> USED_IDS,protected final non-sealed Database#RAW database,public ArrayList<java.lang.Exception> exceptionsList
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/queue/Queue.java
|
Node
|
dequeue
|
class Node<V> {
V value;
Node<V> next;
Node(V obj, Node<V> b) {
value = obj;
next = b;
}
}
boolean isEmpty() {
return size == 0;
}
void enqueue(T obj) {
if (front == null) {
front = new Node<>(obj, null);
rear = front;
} else {
var temp = new Node<>(obj, null);
rear.next = temp;
rear = temp;
}
size++;
}
T dequeue() throws IsEmptyException {<FILL_FUNCTION_BODY>
|
if (isEmpty()) {
throw new IsEmptyException();
} else {
var temp = front;
front = front.next;
size = size - 1;
return temp.value;
}
| 175
| 57
| 232
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java
|
QueueDatabase
|
add
|
class QueueDatabase extends Database<QueueTask> {
private final Queue<QueueTask> data;
public List<Exception> exceptionsList;
public QueueDatabase(Exception... exc) {
this.data = new Queue<>();
this.exceptionsList = new ArrayList<>(List.of(exc));
}
@Override
public QueueTask add(QueueTask t) {<FILL_FUNCTION_BODY>}
/**
* peek method returns object at front without removing it from queue.
*
* @return object at front of queue
* @throws IsEmptyException if queue is empty
*/
public QueueTask peek() throws IsEmptyException {
return this.data.peek();
}
/**
* dequeue method removes the object at front and returns it.
*
* @return object at front of queue
* @throws IsEmptyException if queue is empty
*/
public QueueTask dequeue() throws IsEmptyException {
return this.data.dequeue();
}
@Override
public QueueTask get(String taskId) {
return null;
}
}
|
data.enqueue(t);
return t;
//even if same thing queued twice, it is taken care of in other dbs
| 292
| 37
| 329
|
<methods>public non-sealed void <init>() ,public abstract com.iluwatar.commander.queue.QueueTask add(com.iluwatar.commander.queue.QueueTask) throws com.iluwatar.commander.exceptions.DatabaseUnavailableException,public abstract com.iluwatar.commander.queue.QueueTask get(java.lang.String) throws com.iluwatar.commander.exceptions.DatabaseUnavailableException<variables>
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java
|
QueueTask
|
getType
|
class QueueTask {
/**
* TaskType is the type of task to be done.
*/
public enum TaskType {
MESSAGING,
PAYMENT,
EMPLOYEE_DB
}
public final Order order;
public final TaskType taskType;
public final int messageType; //0-fail, 1-error, 2-success
/*we could have varargs Object instead to pass in any parameter instead of just message type
but keeping it simple here*/
@Getter
@Setter
private long firstAttemptTime = -1L; //when first time attempt made to do task
/**
* getType method.
*
* @return String representing type of task
*/
public String getType() {<FILL_FUNCTION_BODY>}
}
|
if (!this.taskType.equals(TaskType.MESSAGING)) {
return this.taskType.toString();
} else {
if (this.messageType == 0) {
return "Payment Failure Message";
} else if (this.messageType == 1) {
return "Payment Error Message";
} else {
return "Payment Success Message";
}
}
| 209
| 104
| 313
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingService.java
|
ShippingRequest
|
receiveRequest
|
class ShippingRequest {
String transactionId;
String item;
String address;
}
public ShippingService(ShippingDatabase db, Exception... exc) {
super(db, exc);
}
/**
* Public method which will receive request from {@link com.iluwatar.commander.Commander}.
*/
public String receiveRequest(Object... parameters) throws DatabaseUnavailableException {<FILL_FUNCTION_BODY>
|
var id = generateId();
var item = (String) parameters[0];
var address = (String) parameters[1];
var req = new ShippingRequest(id, item, address);
return updateDb(req);
| 114
| 58
| 172
|
<methods>public transient abstract java.lang.String receiveRequest(java.lang.Object[]) throws com.iluwatar.commander.exceptions.DatabaseUnavailableException<variables>private static final java.lang.String ALL_CHARS,private static final java.security.SecureRandom RANDOM,private static final Hashtable<java.lang.String,java.lang.Boolean> USED_IDS,protected final non-sealed Database#RAW database,public ArrayList<java.lang.Exception> exceptionsList
|
iluwatar_java-design-patterns
|
java-design-patterns/component/src/main/java/com/iluwatar/component/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args args command line args.
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
final var player = GameObject.createPlayer();
final var npc = GameObject.createNpc();
LOGGER.info("Player Update:");
player.update(KeyEvent.KEY_LOCATION_LEFT);
LOGGER.info("NPC Update:");
npc.demoUpdate();
| 57
| 80
| 137
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/component/src/main/java/com/iluwatar/component/GameObject.java
|
GameObject
|
createPlayer
|
class GameObject {
private final InputComponent inputComponent;
private final PhysicComponent physicComponent;
private final GraphicComponent graphicComponent;
private final String name;
private int velocity = 0;
private int coordinate = 0;
/**
* Creates a player game object.
*
* @return player object
*/
public static GameObject createPlayer() {<FILL_FUNCTION_BODY>}
/**
* Creates a NPC game object.
*
* @return npc object
*/
public static GameObject createNpc() {
return new GameObject(
new DemoInputComponent(),
new ObjectPhysicComponent(),
new ObjectGraphicComponent(),
"npc");
}
/**
* Updates the three components of the NPC object used in the demo in App.java
* note that this is simply a duplicate of update() without the key event for
* demonstration purposes.
*
* <p>This method is usually used in games if the player becomes inactive.
*/
public void demoUpdate() {
inputComponent.update(this, 0);
physicComponent.update(this);
graphicComponent.update(this);
}
/**
* Updates the three components for objects based on key events.
*
* @param e key event from the player.
*/
public void update(int e) {
inputComponent.update(this, e);
physicComponent.update(this);
graphicComponent.update(this);
}
/**
* Update the velocity based on the acceleration of the GameObject.
*
* @param acceleration the acceleration of the GameObject
*/
public void updateVelocity(int acceleration) {
this.velocity += acceleration;
}
/**
* Set the c based on the current velocity.
*/
public void updateCoordinate() {
this.coordinate += this.velocity;
}
}
|
return new GameObject(new PlayerInputComponent(),
new ObjectPhysicComponent(),
new ObjectGraphicComponent(),
"player");
| 494
| 36
| 530
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/component/src/main/java/com/iluwatar/component/component/inputcomponent/PlayerInputComponent.java
|
PlayerInputComponent
|
update
|
class PlayerInputComponent implements InputComponent {
private static final int WALK_ACCELERATION = 1;
/**
* The update method to change the velocity based on the input key event.
*
* @param gameObject the gameObject instance
* @param e key event instance
*/
@Override
public void update(GameObject gameObject, int e) {<FILL_FUNCTION_BODY>}
}
|
switch (e) {
case KeyEvent.KEY_LOCATION_LEFT -> {
gameObject.updateVelocity(-WALK_ACCELERATION);
LOGGER.info(gameObject.getName() + " has moved left.");
}
case KeyEvent.KEY_LOCATION_RIGHT -> {
gameObject.updateVelocity(WALK_ACCELERATION);
LOGGER.info(gameObject.getName() + " has moved right.");
}
default -> {
LOGGER.info(gameObject.getName() + "'s velocity is unchanged due to the invalid input");
gameObject.updateVelocity(0);
} // incorrect input
}
| 108
| 175
| 283
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java
|
AppServlet
|
doPost
|
class AppServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html";
private String msgPartOne = "<h1>This Server Doesn't Support";
private String msgPartTwo = """
Requests</h1>
<h2>Use a GET request with boolean values for the following parameters<h2>
<h3>'name'</h3>
<h3>'bus'</h3>
<h3>'sports'</h3>
<h3>'sci'</h3>
<h3>'world'</h3>""";
private String destination = "newsDisplay.jsp";
public AppServlet() {
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
try {
RequestDispatcher requestDispatcher = req.getRequestDispatcher(destination);
ClientPropertiesBean reqParams = new ClientPropertiesBean(req);
req.setAttribute("properties", reqParams);
requestDispatcher.forward(req, resp);
} catch (Exception e) {
LOGGER.error("Exception occurred GET request processing ", e);
}
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {<FILL_FUNCTION_BODY>}
@Override
public void doDelete(HttpServletRequest req, HttpServletResponse resp) {
resp.setContentType(CONTENT_TYPE);
try (PrintWriter out = resp.getWriter()) {
out.println(msgPartOne + " Delete " + msgPartTwo);
} catch (Exception e) {
LOGGER.error("Exception occurred DELETE request processing ", e);
}
}
@Override
public void doPut(HttpServletRequest req, HttpServletResponse resp) {
resp.setContentType(CONTENT_TYPE);
try (PrintWriter out = resp.getWriter()) {
out.println(msgPartOne + " Put " + msgPartTwo);
} catch (Exception e) {
LOGGER.error("Exception occurred PUT request processing ", e);
}
}
}
|
resp.setContentType(CONTENT_TYPE);
try (PrintWriter out = resp.getWriter()) {
out.println(msgPartOne + " Post " + msgPartTwo);
} catch (Exception e) {
LOGGER.error("Exception occurred POST request processing ", e);
}
| 528
| 75
| 603
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/composite/src/main/java/com/iluwatar/composite/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var messenger = new Messenger();
LOGGER.info("Message from the orcs: ");
messenger.messageFromOrcs().print();
LOGGER.info("Message from the elves: ");
messenger.messageFromElves().print();
| 56
| 69
| 125
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/composite/src/main/java/com/iluwatar/composite/Messenger.java
|
Messenger
|
messageFromOrcs
|
class Messenger {
LetterComposite messageFromOrcs() {<FILL_FUNCTION_BODY>}
LetterComposite messageFromElves() {
var words = List.of(
new Word('M', 'u', 'c', 'h'),
new Word('w', 'i', 'n', 'd'),
new Word('p', 'o', 'u', 'r', 's'),
new Word('f', 'r', 'o', 'm'),
new Word('y', 'o', 'u', 'r'),
new Word('m', 'o', 'u', 't', 'h')
);
return new Sentence(words);
}
}
|
var words = List.of(
new Word('W', 'h', 'e', 'r', 'e'),
new Word('t', 'h', 'e', 'r', 'e'),
new Word('i', 's'),
new Word('a'),
new Word('w', 'h', 'i', 'p'),
new Word('t', 'h', 'e', 'r', 'e'),
new Word('i', 's'),
new Word('a'),
new Word('w', 'a', 'y')
);
return new Sentence(words);
| 174
| 147
| 321
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/context-object/src/main/java/com/iluwatar/context/object/App.java
|
App
|
main
|
class App {
private static final String SERVICE = "SERVICE";
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
//Initiate first layer and add service information into context
var layerA = new LayerA();
layerA.addAccountInfo(SERVICE);
LOGGER.info("Context = {}", layerA.getContext());
//Initiate second layer and preserving information retrieved in first layer through passing context object
var layerB = new LayerB(layerA);
layerB.addSessionInfo(SERVICE);
LOGGER.info("Context = {}", layerB.getContext());
//Initiate third layer and preserving information retrieved in first and second layer through passing context object
var layerC = new LayerC(layerB);
layerC.addSearchInfo(SERVICE);
LOGGER.info("Context = {}", layerC.getContext());
| 70
| 187
| 257
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/converter/src/main/java/com/iluwatar/converter/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
Converter<UserDto, User> userConverter = new UserConverter();
UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com");
User user = userConverter.convertFromDto(dtoUser);
LOGGER.info("Entity converted from DTO: {}", user);
var users = List.of(
new User("Camile", "Tough", false, "124sad"),
new User("Marti", "Luther", true, "42309fd"),
new User("Kate", "Smith", true, "if0243")
);
LOGGER.info("Domain entities:");
users.stream().map(User::toString).forEach(LOGGER::info);
LOGGER.info("DTO entities converted from domain:");
List<UserDto> dtoEntities = userConverter.createFromEntities(users);
dtoEntities.stream().map(UserDto::toString).forEach(LOGGER::info);
| 56
| 260
| 316
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var commands = new CommandServiceImpl();
// Create Authors and Books using CommandService
commands.authorCreated(AppConstants.E_EVANS, "Eric Evans", "evans@email.com");
commands.authorCreated(AppConstants.J_BLOCH, "Joshua Bloch", "jBloch@email.com");
commands.authorCreated(AppConstants.M_FOWLER, "Martin Fowler", "mFowler@email.com");
commands.bookAddedToAuthor("Domain-Driven Design", 60.08, AppConstants.E_EVANS);
commands.bookAddedToAuthor("Effective Java", 40.54, AppConstants.J_BLOCH);
commands.bookAddedToAuthor("Java Puzzlers", 39.99, AppConstants.J_BLOCH);
commands.bookAddedToAuthor("Java Concurrency in Practice", 29.40, AppConstants.J_BLOCH);
commands.bookAddedToAuthor("Patterns of Enterprise"
+ " Application Architecture", 54.01, AppConstants.M_FOWLER);
commands.bookAddedToAuthor("Domain Specific Languages", 48.89, AppConstants.M_FOWLER);
commands.authorNameUpdated(AppConstants.E_EVANS, "Eric J. Evans");
var queries = new QueryServiceImpl();
// Query the database using QueryService
var nullAuthor = queries.getAuthorByUsername("username");
var evans = queries.getAuthorByUsername(AppConstants.E_EVANS);
var blochBooksCount = queries.getAuthorBooksCount(AppConstants.J_BLOCH);
var authorsCount = queries.getAuthorsCount();
var dddBook = queries.getBook("Domain-Driven Design");
var blochBooks = queries.getAuthorBooks(AppConstants.J_BLOCH);
LOGGER.info("Author username : {}", nullAuthor);
LOGGER.info("Author evans : {}", evans);
LOGGER.info("jBloch number of books : {}", blochBooksCount);
LOGGER.info("Number of authors : {}", authorsCount);
LOGGER.info("DDD book : {}", dddBook);
LOGGER.info("jBloch books : {}", blochBooks);
HibernateUtil.getSessionFactory().close();
| 57
| 603
| 660
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java
|
CommandServiceImpl
|
bookTitleUpdated
|
class CommandServiceImpl implements CommandService {
private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
private Author getAuthorByUsername(String username) {
Author author;
try (var session = sessionFactory.openSession()) {
var query = session.createQuery("from Author where username=:username");
query.setParameter("username", username);
author = (Author) query.uniqueResult();
}
if (author == null) {
HibernateUtil.getSessionFactory().close();
throw new NullPointerException("Author " + username + " doesn't exist!");
}
return author;
}
private Book getBookByTitle(String title) {
Book book;
try (var session = sessionFactory.openSession()) {
var query = session.createQuery("from Book where title=:title");
query.setParameter("title", title);
book = (Book) query.uniqueResult();
}
if (book == null) {
HibernateUtil.getSessionFactory().close();
throw new NullPointerException("Book " + title + " doesn't exist!");
}
return book;
}
@Override
public void authorCreated(String username, String name, String email) {
var author = new Author(username, name, email);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.save(author);
session.getTransaction().commit();
}
}
@Override
public void bookAddedToAuthor(String title, double price, String username) {
var author = getAuthorByUsername(username);
var book = new Book(title, price, author);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.save(book);
session.getTransaction().commit();
}
}
@Override
public void authorNameUpdated(String username, String name) {
var author = getAuthorByUsername(username);
author.setName(name);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.update(author);
session.getTransaction().commit();
}
}
@Override
public void authorUsernameUpdated(String oldUsername, String newUsername) {
var author = getAuthorByUsername(oldUsername);
author.setUsername(newUsername);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.update(author);
session.getTransaction().commit();
}
}
@Override
public void authorEmailUpdated(String username, String email) {
var author = getAuthorByUsername(username);
author.setEmail(email);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.update(author);
session.getTransaction().commit();
}
}
@Override
public void bookTitleUpdated(String oldTitle, String newTitle) {<FILL_FUNCTION_BODY>}
@Override
public void bookPriceUpdated(String title, double price) {
var book = getBookByTitle(title);
book.setPrice(price);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.update(book);
session.getTransaction().commit();
}
}
}
|
var book = getBookByTitle(oldTitle);
book.setTitle(newTitle);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.update(book);
session.getTransaction().commit();
}
| 854
| 67
| 921
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java
|
QueryServiceImpl
|
getBook
|
class QueryServiceImpl implements QueryService {
private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
@Override
public Author getAuthorByUsername(String username) {
Author authorDto;
try (var session = sessionFactory.openSession()) {
Query<Author> sqlQuery = session.createQuery(
"select new com.iluwatar.cqrs.dto.Author(a.name, a.email, a.username)"
+ " from com.iluwatar.cqrs.domain.model.Author a where a.username=:username");
sqlQuery.setParameter(AppConstants.USER_NAME, username);
authorDto = sqlQuery.uniqueResult();
}
return authorDto;
}
@Override
public Book getBook(String title) {<FILL_FUNCTION_BODY>}
@Override
public List<Book> getAuthorBooks(String username) {
List<Book> bookDtos;
try (var session = sessionFactory.openSession()) {
Query<Book> sqlQuery = session.createQuery(
"select new com.iluwatar.cqrs.dto.Book(b.title, b.price)"
+ " from com.iluwatar.cqrs.domain.model.Author a, com.iluwatar.cqrs.domain.model.Book b "
+ "where b.author.id = a.id and a.username=:username");
sqlQuery.setParameter(AppConstants.USER_NAME, username);
bookDtos = sqlQuery.list();
}
return bookDtos;
}
@Override
public BigInteger getAuthorBooksCount(String username) {
BigInteger bookcount;
try (var session = sessionFactory.openSession()) {
var sqlQuery = session.createNativeQuery(
"SELECT count(b.title)" + " FROM Book b, Author a"
+ " where b.author_id = a.id and a.username=:username");
sqlQuery.setParameter(AppConstants.USER_NAME, username);
bookcount = (BigInteger) sqlQuery.uniqueResult();
}
return bookcount;
}
@Override
public BigInteger getAuthorsCount() {
BigInteger authorcount;
try (var session = sessionFactory.openSession()) {
var sqlQuery = session.createNativeQuery("SELECT count(id) from Author");
authorcount = (BigInteger) sqlQuery.uniqueResult();
}
return authorcount;
}
}
|
Book bookDto;
try (var session = sessionFactory.openSession()) {
Query<Book> sqlQuery = session.createQuery(
"select new com.iluwatar.cqrs.dto.Book(b.title, b.price)"
+ " from com.iluwatar.cqrs.domain.model.Book b where b.title=:title");
sqlQuery.setParameter("title", title);
bookDto = sqlQuery.uniqueResult();
}
return bookDto;
| 636
| 131
| 767
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java
|
HibernateUtil
|
buildSessionFactory
|
class HibernateUtil {
private static final SessionFactory SESSIONFACTORY = buildSessionFactory();
private static SessionFactory buildSessionFactory() {<FILL_FUNCTION_BODY>}
public static SessionFactory getSessionFactory() {
return SESSIONFACTORY;
}
}
|
// configures settings from hibernate.cfg.xml
final var registry = new StandardServiceRegistryBuilder().configure().build();
try {
return new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception ex) {
StandardServiceRegistryBuilder.destroy(registry);
LOGGER.error("Initial SessionFactory creation failed.", ex);
throw new ExceptionInInitializerError(ex);
}
| 76
| 108
| 184
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/crtp/src/main/java/crtp/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
MmaBantamweightFighter fighter1 = new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai");
MmaBantamweightFighter fighter2 = new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo");
fighter1.fight(fighter2);
MmaHeavyweightFighter fighter3 = new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing");
MmaHeavyweightFighter fighter4 = new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu");
fighter3.fight(fighter4);
| 56
| 206
| 262
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/crtp/src/main/java/crtp/MmaFighter.java
|
MmaFighter
|
fight
|
class MmaFighter<T extends MmaFighter<T>> implements Fighter<T> {
private final String name;
private final String surname;
private final String nickName;
private final String speciality;
@Override
public void fight(T opponent) {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("{} is going to fight against {}", this, opponent);
| 96
| 24
| 120
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/currying/src/main/java/com/iluwatar/currying/App.java
|
App
|
main
|
class App {
/**
* Main entry point of the program.
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Librarian begins their work.");
// Defining genre book functions
Book.AddAuthor fantasyBookFunc = Book.builder().withGenre(Genre.FANTASY);
Book.AddAuthor horrorBookFunc = Book.builder().withGenre(Genre.HORROR);
Book.AddAuthor scifiBookFunc = Book.builder().withGenre(Genre.SCIFI);
// Defining author book functions
Book.AddTitle kingFantasyBooksFunc = fantasyBookFunc.withAuthor("Stephen King");
Book.AddTitle kingHorrorBooksFunc = horrorBookFunc.withAuthor("Stephen King");
Book.AddTitle rowlingFantasyBooksFunc = fantasyBookFunc.withAuthor("J.K. Rowling");
// Creates books by Stephen King (horror and fantasy genres)
Book shining = kingHorrorBooksFunc.withTitle("The Shining")
.withPublicationDate(LocalDate.of(1977, 1, 28));
Book darkTower = kingFantasyBooksFunc.withTitle("The Dark Tower: Gunslinger")
.withPublicationDate(LocalDate.of(1982, 6, 10));
// Creates fantasy books by J.K. Rowling
Book chamberOfSecrets = rowlingFantasyBooksFunc.withTitle("Harry Potter and the Chamber of Secrets")
.withPublicationDate(LocalDate.of(1998, 7, 2));
// Create sci-fi books
Book dune = scifiBookFunc.withAuthor("Frank Herbert")
.withTitle("Dune")
.withPublicationDate(LocalDate.of(1965, 8, 1));
Book foundation = scifiBookFunc.withAuthor("Isaac Asimov")
.withTitle("Foundation")
.withPublicationDate(LocalDate.of(1942, 5, 1));
LOGGER.info("Stephen King Books:");
LOGGER.info(shining.toString());
LOGGER.info(darkTower.toString());
LOGGER.info("J.K. Rowling Books:");
LOGGER.info(chamberOfSecrets.toString());
LOGGER.info("Sci-fi Books:");
LOGGER.info(dune.toString());
LOGGER.info(foundation.toString());
| 46
| 598
| 644
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/currying/src/main/java/com/iluwatar/currying/Book.java
|
Book
|
toString
|
class Book {
private final Genre genre;
private final String author;
private final String title;
private final LocalDate publicationDate;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Book book = (Book) o;
return Objects.equals(author, book.author)
&& Objects.equals(genre, book.genre)
&& Objects.equals(title, book.title)
&& Objects.equals(publicationDate, book.publicationDate);
}
@Override
public int hashCode() {
return Objects.hash(author, genre, title, publicationDate);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
/**
* Curried book builder/creator function.
*/
static Function<Genre, Function<String, Function<String, Function<LocalDate, Book>>>> book_creator
= bookGenre
-> bookAuthor
-> bookTitle
-> bookPublicationDate
-> new Book(bookGenre, bookAuthor, bookTitle, bookPublicationDate);
/**
* Implements the builder pattern using functional interfaces to create a more readable book
* creator function. This function is equivalent to the BOOK_CREATOR function.
*/
public static AddGenre builder() {
return genre
-> author
-> title
-> publicationDate
-> new Book(genre, author, title, publicationDate);
}
/**
* Functional interface which adds the genre to a book.
*/
public interface AddGenre {
Book.AddAuthor withGenre(Genre genre);
}
/**
* Functional interface which adds the author to a book.
*/
public interface AddAuthor {
Book.AddTitle withAuthor(String author);
}
/**
* Functional interface which adds the title to a book.
*/
public interface AddTitle {
Book.AddPublicationDate withTitle(String title);
}
/**
* Functional interface which adds the publication date to a book.
*/
public interface AddPublicationDate {
Book withPublicationDate(LocalDate publicationDate);
}
}
|
return "Book{" + "genre=" + genre + ", author='" + author + '\''
+ ", title='" + title + '\'' + ", publicationDate=" + publicationDate + '}';
| 600
| 52
| 652
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/dao/src/main/java/com/iluwatar/dao/App.java
|
App
|
performOperationsUsing
|
class App {
private static final String DB_URL = "jdbc:h2:mem:dao;DB_CLOSE_DELAY=-1";
private static final String ALL_CUSTOMERS = "customerDao.getAllCustomers(): ";
/**
* Program entry point.
*
* @param args command line args.
* @throws Exception if any error occurs.
*/
public static void main(final String[] args) throws Exception {
final var inMemoryDao = new InMemoryCustomerDao();
performOperationsUsing(inMemoryDao);
final var dataSource = createDataSource();
createSchema(dataSource);
final var dbDao = new DbCustomerDao(dataSource);
performOperationsUsing(dbDao);
deleteSchema(dataSource);
}
private static void deleteSchema(DataSource dataSource) throws SQLException {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL);
}
}
private static void createSchema(DataSource dataSource) throws SQLException {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL);
}
}
private static DataSource createDataSource() {
var dataSource = new JdbcDataSource();
dataSource.setURL(DB_URL);
return dataSource;
}
private static void performOperationsUsing(final CustomerDao customerDao) throws Exception {<FILL_FUNCTION_BODY>}
private static void addCustomers(CustomerDao customerDao) throws Exception {
for (var customer : generateSampleCustomers()) {
customerDao.add(customer);
}
}
/**
* Generate customers.
*
* @return list of customers.
*/
public static List<Customer> generateSampleCustomers() {
final var customer1 = new Customer(1, "Adam", "Adamson");
final var customer2 = new Customer(2, "Bob", "Bobson");
final var customer3 = new Customer(3, "Carl", "Carlson");
return List.of(customer1, customer2, customer3);
}
}
|
addCustomers(customerDao);
LOGGER.info(ALL_CUSTOMERS);
try (var customerStream = customerDao.getAll()) {
customerStream.forEach(customer -> LOGGER.info(customer.toString()));
}
LOGGER.info("customerDao.getCustomerById(2): " + customerDao.getById(2));
final var customer = new Customer(4, "Dan", "Danson");
customerDao.add(customer);
LOGGER.info(ALL_CUSTOMERS + customerDao.getAll());
customer.setFirstName("Daniel");
customer.setLastName("Danielson");
customerDao.update(customer);
LOGGER.info(ALL_CUSTOMERS);
try (var customerStream = customerDao.getAll()) {
customerStream.forEach(cust -> LOGGER.info(cust.toString()));
}
customerDao.delete(customer);
LOGGER.info(ALL_CUSTOMERS + customerDao.getAll());
| 588
| 261
| 849
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java
|
DbCustomerDao
|
getAll
|
class DbCustomerDao implements CustomerDao {
private final DataSource dataSource;
/**
* Get all customers as Java Stream.
*
* @return a lazily populated stream of customers. Note the stream returned must be closed to free
* all the acquired resources. The stream keeps an open connection to the database till it is
* complete or is closed manually.
*/
@Override
public Stream<Customer> getAll() throws Exception {<FILL_FUNCTION_BODY>}
private Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet) {
try {
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
LOGGER.info("Exception thrown " + e.getMessage());
}
}
private Customer createCustomer(ResultSet resultSet) throws SQLException {
return new Customer(resultSet.getInt("ID"),
resultSet.getString("FNAME"),
resultSet.getString("LNAME"));
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Customer> getById(int id) throws Exception {
ResultSet resultSet = null;
try (var connection = getConnection();
var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) {
statement.setInt(1, id);
resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(createCustomer(resultSet));
} else {
return Optional.empty();
}
} catch (SQLException ex) {
throw new CustomException(ex.getMessage(), ex);
} finally {
if (resultSet != null) {
resultSet.close();
}
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean add(Customer customer) throws Exception {
if (getById(customer.getId()).isPresent()) {
return false;
}
try (var connection = getConnection();
var statement = connection.prepareStatement("INSERT INTO CUSTOMERS VALUES (?,?,?)")) {
statement.setInt(1, customer.getId());
statement.setString(2, customer.getFirstName());
statement.setString(3, customer.getLastName());
statement.execute();
return true;
} catch (SQLException ex) {
throw new CustomException(ex.getMessage(), ex);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean update(Customer customer) throws Exception {
try (var connection = getConnection();
var statement =
connection
.prepareStatement("UPDATE CUSTOMERS SET FNAME = ?, LNAME = ? WHERE ID = ?")) {
statement.setString(1, customer.getFirstName());
statement.setString(2, customer.getLastName());
statement.setInt(3, customer.getId());
return statement.executeUpdate() > 0;
} catch (SQLException ex) {
throw new CustomException(ex.getMessage(), ex);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean delete(Customer customer) throws Exception {
try (var connection = getConnection();
var statement = connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) {
statement.setInt(1, customer.getId());
return statement.executeUpdate() > 0;
} catch (SQLException ex) {
throw new CustomException(ex.getMessage(), ex);
}
}
}
|
try {
var connection = getConnection();
var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS"); // NOSONAR
var resultSet = statement.executeQuery(); // NOSONAR
return StreamSupport.stream(new Spliterators.AbstractSpliterator<Customer>(Long.MAX_VALUE,
Spliterator.ORDERED) {
@Override
public boolean tryAdvance(Consumer<? super Customer> action) {
try {
if (!resultSet.next()) {
return false;
}
action.accept(createCustomer(resultSet));
return true;
} catch (SQLException e) {
throw new RuntimeException(e); // NOSONAR
}
}
}, false).onClose(() -> mutedClose(connection, statement, resultSet));
} catch (SQLException e) {
throw new CustomException(e.getMessage(), e);
}
| 924
| 230
| 1,154
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java
|
InMemoryCustomerDao
|
add
|
class InMemoryCustomerDao implements CustomerDao {
private final Map<Integer, Customer> idToCustomer = new HashMap<>();
/**
* An eagerly evaluated stream of customers stored in memory.
*/
@Override
public Stream<Customer> getAll() {
return idToCustomer.values().stream();
}
@Override
public Optional<Customer> getById(final int id) {
return Optional.ofNullable(idToCustomer.get(id));
}
@Override
public boolean add(final Customer customer) {<FILL_FUNCTION_BODY>}
@Override
public boolean update(final Customer customer) {
return idToCustomer.replace(customer.getId(), customer) != null;
}
@Override
public boolean delete(final Customer customer) {
return idToCustomer.remove(customer.getId()) != null;
}
}
|
if (getById(customer.getId()).isPresent()) {
return false;
}
idToCustomer.put(customer.getId(), customer);
return true;
| 224
| 46
| 270
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/data-bus/src/main/java/com/iluwatar/databus/App.java
|
App
|
main
|
class App {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
final var bus = DataBus.getInstance();
bus.subscribe(new StatusMember(1));
bus.subscribe(new StatusMember(2));
final var foo = new MessageCollectorMember("Foo");
final var bar = new MessageCollectorMember("Bar");
bus.subscribe(foo);
bus.publish(StartingData.of(LocalDateTime.now()));
bus.publish(MessageData.of("Only Foo should see this"));
bus.subscribe(bar);
bus.publish(MessageData.of("Foo and Bar should see this"));
bus.unsubscribe(foo);
bus.publish(MessageData.of("Only Bar should see this"));
bus.publish(StoppingData.of(LocalDateTime.now()));
| 31
| 185
| 216
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java
|
StatusMember
|
handleEvent
|
class StatusMember implements Member {
private final int id;
private LocalDateTime started;
private LocalDateTime stopped;
@Override
public void accept(final DataType data) {
if (data instanceof StartingData) {
handleEvent((StartingData) data);
} else if (data instanceof StoppingData) {
handleEvent((StoppingData) data);
}
}
private void handleEvent(StartingData data) {
started = data.getWhen();
LOGGER.info("Receiver {} sees application started at {}", id, started);
}
private void handleEvent(StoppingData data) {<FILL_FUNCTION_BODY>}
}
|
stopped = data.getWhen();
LOGGER.info("Receiver {} sees application stopping at {}", id, stopped);
LOGGER.info("Receiver {} sending goodbye message", id);
data.getDataBus().publish(MessageData.of(String.format("Goodbye cruel world from #%d!", id)));
| 174
| 81
| 255
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/data-locality/src/main/java/com/iluwatar/data/locality/Application.java
|
Application
|
main
|
class Application {
private static final int NUM_ENTITIES = 5;
/**
* Start game loop with each component have NUM_ENTITIES instance.
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Start Game Application using Data-Locality pattern");
var gameEntity = new GameEntity(NUM_ENTITIES);
gameEntity.start();
gameEntity.update();
| 71
| 50
| 121
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/data-locality/src/main/java/com/iluwatar/data/locality/game/GameEntity.java
|
GameEntity
|
update
|
class GameEntity {
private final AiComponentManager aiComponentManager;
private final PhysicsComponentManager physicsComponentManager;
private final RenderComponentManager renderComponentManager;
/**
* Init components.
*/
public GameEntity(int numEntities) {
LOGGER.info("Init Game with #Entity : {}", numEntities);
aiComponentManager = new AiComponentManager(numEntities);
physicsComponentManager = new PhysicsComponentManager(numEntities);
renderComponentManager = new RenderComponentManager(numEntities);
}
/**
* start all component.
*/
public void start() {
LOGGER.info("Start Game");
aiComponentManager.start();
physicsComponentManager.start();
renderComponentManager.start();
}
/**
* update all component.
*/
public void update() {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Update Game Component");
// Process AI.
aiComponentManager.update();
// update physics.
physicsComponentManager.update();
// Draw to screen.
renderComponentManager.render();
| 234
| 60
| 294
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java
|
AiComponentManager
|
update
|
class AiComponentManager {
private static final int MAX_ENTITIES = 10000;
private final int numEntities;
private final Component[] aiComponents = new AiComponent[MAX_ENTITIES];
public AiComponentManager(int numEntities) {
this.numEntities = numEntities;
}
/**
* start AI component of Game.
*/
public void start() {
LOGGER.info("Start AI Game Component");
IntStream.range(0, numEntities).forEach(i -> aiComponents[i] = new AiComponent());
}
/**
* Update AI component of Game.
*/
public void update() {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Update AI Game Component");
IntStream.range(0, numEntities)
.filter(i -> aiComponents.length > i && aiComponents[i] != null)
.forEach(i -> aiComponents[i].update());
| 195
| 73
| 268
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java
|
PhysicsComponentManager
|
update
|
class PhysicsComponentManager {
private static final int MAX_ENTITIES = 10000;
private final int numEntities;
private final Component[] physicsComponents = new PhysicsComponent[MAX_ENTITIES];
public PhysicsComponentManager(int numEntities) {
this.numEntities = numEntities;
}
/**
* Start physics component of Game.
*/
public void start() {
LOGGER.info("Start Physics Game Component ");
IntStream.range(0, numEntities).forEach(i -> physicsComponents[i] = new PhysicsComponent());
}
/**
* Update physics component of Game.
*/
public void update() {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Update Physics Game Component ");
// Process physics.
IntStream.range(0, numEntities)
.filter(i -> physicsComponents.length > i && physicsComponents[i] != null)
.forEach(i -> physicsComponents[i].update());
| 195
| 77
| 272
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java
|
RenderComponentManager
|
render
|
class RenderComponentManager {
private static final int MAX_ENTITIES = 10000;
private final int numEntities;
private final Component[] renderComponents = new RenderComponent[MAX_ENTITIES];
public RenderComponentManager(int numEntities) {
this.numEntities = numEntities;
}
/**
* Start render component.
*/
public void start() {
LOGGER.info("Start Render Game Component ");
IntStream.range(0, numEntities).forEach(i -> renderComponents[i] = new RenderComponent());
}
/**
* render component.
*/
public void render() {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Update Render Game Component ");
// Process Render.
IntStream.range(0, numEntities)
.filter(i -> renderComponents.length > i && renderComponents[i] != null)
.forEach(i -> renderComponents[i].render());
| 190
| 78
| 268
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/data-mapper/src/main/java/com/iluwatar/datamapper/App.java
|
App
|
main
|
class App {
private static final String STUDENT_STRING = "App.main(), student : ";
/**
* Program entry point.
*
* @param args command line args.
*/
public static void main(final String... args) {<FILL_FUNCTION_BODY>}
private App() {
}
}
|
/* Create new data mapper for type 'first' */
final var mapper = new StudentDataMapperImpl();
/* Create new student */
var student = new Student(1, "Adam", 'A');
/* Add student in respectibe store */
mapper.insert(student);
LOGGER.debug(STUDENT_STRING + student + ", is inserted");
/* Find this student */
final var studentToBeFound = mapper.find(student.getStudentId());
LOGGER.debug(STUDENT_STRING + studentToBeFound + ", is searched");
/* Update existing student object */
student = new Student(student.getStudentId(), "AdamUpdated", 'A');
/* Update student in respectibe db */
mapper.update(student);
LOGGER.debug(STUDENT_STRING + student + ", is updated");
LOGGER.debug(STUDENT_STRING + student + ", is going to be deleted");
/* Delete student in db */
mapper.delete(student);
| 89
| 266
| 355
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java
|
StudentDataMapperImpl
|
insert
|
class StudentDataMapperImpl implements StudentDataMapper {
/* Note: Normally this would be in the form of an actual database */
private final List<Student> students = new ArrayList<>();
@Override
public Optional<Student> find(int studentId) {
return this.getStudents().stream().filter(x -> x.getStudentId() == studentId).findFirst();
}
@Override
public void update(Student studentToBeUpdated) throws DataMapperException {
String name = studentToBeUpdated.getName();
Integer index = Optional.of(studentToBeUpdated)
.map(Student::getStudentId)
.flatMap(this::find)
.map(students::indexOf)
.orElseThrow(() -> new DataMapperException("Student [" + name + "] is not found"));
students.set(index, studentToBeUpdated);
}
@Override
public void insert(Student studentToBeInserted) throws DataMapperException {<FILL_FUNCTION_BODY>}
@Override
public void delete(Student studentToBeDeleted) throws DataMapperException {
if (!students.remove(studentToBeDeleted)) {
String name = studentToBeDeleted.getName();
throw new DataMapperException("Student [" + name + "] is not found");
}
}
}
|
Optional<Student> student = find(studentToBeInserted.getStudentId());
if (student.isPresent()) {
String name = studentToBeInserted.getName();
throw new DataMapperException("Student already [" + name + "] exists");
}
students.add(studentToBeInserted);
| 342
| 86
| 428
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java
|
App
|
main
|
class App {
/**
* Method as act client and request to server for details.
*
* @param args program argument.
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
private static void printCustomerDetails(List<CustomerDto> allCustomers) {
allCustomers.forEach(customer -> LOGGER.info(customer.firstName()));
}
}
|
// Example 1: Customer DTO
var customerOne = new CustomerDto("1", "Kelly", "Brown");
var customerTwo = new CustomerDto("2", "Alfonso", "Bass");
var customers = new ArrayList<>(List.of(customerOne, customerTwo));
var customerResource = new CustomerResource(customers);
LOGGER.info("All customers:");
var allCustomers = customerResource.customers();
printCustomerDetails(allCustomers);
LOGGER.info("----------------------------------------------------------");
LOGGER.info("Deleting customer with id {1}");
customerResource.delete(customerOne.id());
allCustomers = customerResource.customers();
printCustomerDetails(allCustomers);
LOGGER.info("----------------------------------------------------------");
LOGGER.info("Adding customer three}");
var customerThree = new CustomerDto("3", "Lynda", "Blair");
customerResource.save(customerThree);
allCustomers = customerResource.customers();
printCustomerDetails(allCustomers);
// Example 2: Product DTO
Product tv = Product.builder().id(1L).name("TV").supplier("Sony").price(1000D).cost(1090D).build();
Product microwave =
Product.builder()
.id(2L)
.name("microwave")
.supplier("Delonghi")
.price(1000D)
.cost(1090D).build();
Product refrigerator =
Product.builder()
.id(3L)
.name("refrigerator")
.supplier("Botsch")
.price(1000D)
.cost(1090D).build();
Product airConditioner =
Product.builder()
.id(4L)
.name("airConditioner")
.supplier("LG")
.price(1000D)
.cost(1090D).build();
List<Product> products =
new ArrayList<>(Arrays.asList(tv, microwave, refrigerator, airConditioner));
ProductResource productResource = new ProductResource(products);
LOGGER.info(
"####### List of products including sensitive data just for admins: \n {}",
Arrays.toString(productResource.getAllProductsForAdmin().toArray()));
LOGGER.info(
"####### List of products for customers: \n {}",
Arrays.toString(productResource.getAllProductsForCustomer().toArray()));
LOGGER.info("####### Going to save Sony PS5 ...");
ProductDto.Request.Create createProductRequestDto =
new ProductDto.Request.Create()
.setName("PS5")
.setCost(1000D)
.setPrice(1220D)
.setSupplier("Sony");
productResource.save(createProductRequestDto);
LOGGER.info(
"####### List of products after adding PS5: {}",
Arrays.toString(productResource.products().toArray()));
| 108
| 784
| 892
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java
|
Product
|
toString
|
class Product {
private Long id;
private String name;
private Double price;
private Double cost;
private String supplier;
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Product{"
+ "id=" + id
+ ", name='" + name + '\''
+ ", price=" + price
+ ", cost=" + cost
+ ", supplier='" + supplier + '\''
+ '}';
| 61
| 66
| 127
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/decorator/src/main/java/com/iluwatar/decorator/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// simple troll
LOGGER.info("A simple looking troll approaches.");
var troll = new SimpleTroll();
troll.attack();
troll.fleeBattle();
LOGGER.info("Simple troll power: {}.\n", troll.getAttackPower());
// change the behavior of the simple troll by adding a decorator
LOGGER.info("A troll with huge club surprises you.");
var clubbedTroll = new ClubbedTroll(troll);
clubbedTroll.attack();
clubbedTroll.fleeBattle();
LOGGER.info("Clubbed troll power: {}.\n", clubbedTroll.getAttackPower());
| 56
| 180
| 236
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java
|
ClubbedTroll
|
attack
|
class ClubbedTroll implements Troll {
private final Troll decorated;
@Override
public void attack() {<FILL_FUNCTION_BODY>}
@Override
public int getAttackPower() {
return decorated.getAttackPower() + 10;
}
@Override
public void fleeBattle() {
decorated.fleeBattle();
}
}
|
decorated.attack();
LOGGER.info("The troll swings at you with a club!");
| 103
| 29
| 132
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/delegation/src/main/java/com/iluwatar/delegation/simple/App.java
|
App
|
main
|
class App {
private static final String MESSAGE_TO_PRINT = "hello world";
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var hpPrinterController = new PrinterController(new HpPrinter());
var canonPrinterController = new PrinterController(new CanonPrinter());
var epsonPrinterController = new PrinterController(new EpsonPrinter());
hpPrinterController.print(MESSAGE_TO_PRINT);
canonPrinterController.print(MESSAGE_TO_PRINT);
epsonPrinterController.print(MESSAGE_TO_PRINT);
| 77
| 120
| 197
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var simpleWizard = new SimpleWizard();
simpleWizard.smoke();
var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco());
advancedWizard.smoke();
var advancedSorceress = new AdvancedSorceress();
advancedSorceress.setTobacco(new SecondBreakfastTobacco());
advancedSorceress.smoke();
var injector = Guice.createInjector(new TobaccoModule());
var guiceWizard = injector.getInstance(GuiceWizard.class);
guiceWizard.smoke();
| 56
| 153
| 209
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java
|
App
|
run
|
class App {
/**
* Program execution point.
*/
public void run() {<FILL_FUNCTION_BODY>}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var app = new App();
app.run();
}
}
|
final var executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
final World world = new World();
@Override
public void run() {
var countries = world.fetch();
LOGGER.info("Our world currently has the following countries:-");
countries.stream().map(country -> "\t" + country).forEach(LOGGER::info);
}
}, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds.
| 95
| 138
| 233
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java
|
DataFetcher
|
fetch
|
class DataFetcher {
private static final String FILENAME = "world.txt";
private long lastFetched;
public DataFetcher() {
this.lastFetched = -1;
}
private boolean isDirty(long fileLastModified) {
if (lastFetched != fileLastModified) {
lastFetched = fileLastModified;
return true;
}
return false;
}
/**
* Fetches data/content from raw file.
*
* @return List of strings
*/
public List<String> fetch() {<FILL_FUNCTION_BODY>}
}
|
var classLoader = getClass().getClassLoader();
var file = new File(classLoader.getResource(FILENAME).getFile());
if (isDirty(file.lastModified())) {
LOGGER.info(FILENAME + " is dirty! Re-fetching file content...");
try (var br = new BufferedReader(new FileReader(file))) {
return br.lines().collect(Collectors.collectingAndThen(Collectors.toList(), List::copyOf));
} catch (IOException e) {
LOGGER.error("An error occurred: ", e);
}
}
return List.of();
| 171
| 158
| 329
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java
|
World
|
fetch
|
class World {
private List<String> countries;
private final DataFetcher df;
public World() {
this.countries = new ArrayList<>();
this.df = new DataFetcher();
}
/**
* Calls {@link DataFetcher} to fetch data from back-end.
*
* @return List of strings
*/
public List<String> fetch() {<FILL_FUNCTION_BODY>}
}
|
var data = df.fetch();
countries = data.isEmpty() ? countries : data;
return countries;
| 119
| 30
| 149
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/domain-model/src/main/java/com/iluwatar/domainmodel/App.java
|
App
|
main
|
class App {
public static final String H2_DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";
public static final String CREATE_SCHEMA_SQL =
"CREATE TABLE CUSTOMERS (name varchar primary key, money decimal);"
+ "CREATE TABLE PRODUCTS (name varchar primary key, price decimal, expiration_date date);"
+ "CREATE TABLE PURCHASES ("
+ "product_name varchar references PRODUCTS(name),"
+ "customer_name varchar references CUSTOMERS(name));";
public static final String DELETE_SCHEMA_SQL =
"DROP TABLE PURCHASES IF EXISTS;"
+ "DROP TABLE CUSTOMERS IF EXISTS;"
+ "DROP TABLE PRODUCTS IF EXISTS;";
/**
* Program entry point.
*
* @param args command line arguments
* @throws Exception if any error occurs
*/
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
private static DataSource createDataSource() {
var dataSource = new JdbcDataSource();
dataSource.setUrl(H2_DB_URL);
return dataSource;
}
private static void deleteSchema(DataSource dataSource) throws SQLException {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(DELETE_SCHEMA_SQL);
}
}
private static void createSchema(DataSource dataSource) throws SQLException {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(CREATE_SCHEMA_SQL);
}
}
}
|
// Create data source and create the customers, products and purchases tables
final var dataSource = createDataSource();
deleteSchema(dataSource);
createSchema(dataSource);
// create customer
var customerDao = new CustomerDaoImpl(dataSource);
var tom =
Customer.builder()
.name("Tom")
.money(Money.of(USD, 30))
.customerDao(customerDao)
.build();
tom.save();
// create products
var productDao = new ProductDaoImpl(dataSource);
var eggs =
Product.builder()
.name("Eggs")
.price(Money.of(USD, 10.0))
.expirationDate(LocalDate.now().plusDays(7))
.productDao(productDao)
.build();
var butter =
Product.builder()
.name("Butter")
.price(Money.of(USD, 20.00))
.expirationDate(LocalDate.now().plusDays(9))
.productDao(productDao)
.build();
var cheese =
Product.builder()
.name("Cheese")
.price(Money.of(USD, 25.0))
.expirationDate(LocalDate.now().plusDays(2))
.productDao(productDao)
.build();
eggs.save();
butter.save();
cheese.save();
// show money balance of customer after each purchase
tom.showBalance();
tom.showPurchases();
// buy eggs
tom.buyProduct(eggs);
tom.showBalance();
// buy butter
tom.buyProduct(butter);
tom.showBalance();
// trying to buy cheese, but receive a refusal
// because he didn't have enough money
tom.buyProduct(cheese);
tom.showBalance();
// return butter and get money back
tom.returnProduct(butter);
tom.showBalance();
// Tom can buy cheese now because he has enough money
// and there is a discount on cheese because it expires in 2 days
tom.buyProduct(cheese);
tom.save();
// show money balance and purchases after shopping
tom.showBalance();
tom.showPurchases();
| 448
| 618
| 1,066
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/domain-model/src/main/java/com/iluwatar/domainmodel/Customer.java
|
Customer
|
showPurchases
|
class Customer {
@NonNull private final CustomerDao customerDao;
@Builder.Default private List<Product> purchases = new ArrayList<>();
@NonNull private String name;
@NonNull private Money money;
/**
* Save customer or update if customer already exist.
*/
public void save() {
try {
Optional<Customer> customer = customerDao.findByName(name);
if (customer.isPresent()) {
customerDao.update(this);
} else {
customerDao.save(this);
}
} catch (SQLException ex) {
LOGGER.error(ex.getMessage());
}
}
/**
* Add product to purchases, save to db and withdraw money.
*
* @param product to buy.
*/
public void buyProduct(Product product) {
LOGGER.info(
String.format(
"%s want to buy %s($%.2f)...",
name, product.getName(), product.getSalePrice().getAmount()));
try {
withdraw(product.getSalePrice());
} catch (IllegalArgumentException ex) {
LOGGER.error(ex.getMessage());
return;
}
try {
customerDao.addProduct(product, this);
purchases.add(product);
LOGGER.info(String.format("%s bought %s!", name, product.getName()));
} catch (SQLException exception) {
receiveMoney(product.getSalePrice());
LOGGER.error(exception.getMessage());
}
}
/**
* Remove product from purchases, delete from db and return money.
*
* @param product to return.
*/
public void returnProduct(Product product) {
LOGGER.info(
String.format(
"%s want to return %s($%.2f)...",
name, product.getName(), product.getSalePrice().getAmount()));
if (purchases.contains(product)) {
try {
customerDao.deleteProduct(product, this);
purchases.remove(product);
receiveMoney(product.getSalePrice());
LOGGER.info(String.format("%s returned %s!", name, product.getName()));
} catch (SQLException ex) {
LOGGER.error(ex.getMessage());
}
} else {
LOGGER.error(String.format("%s didn't buy %s...", name, product.getName()));
}
}
/**
* Print customer's purchases.
*/
public void showPurchases() {<FILL_FUNCTION_BODY>}
/**
* Print customer's money balance.
*/
public void showBalance() {
LOGGER.info(name + " balance: " + money);
}
private void withdraw(Money amount) throws IllegalArgumentException {
if (money.compareTo(amount) < 0) {
throw new IllegalArgumentException("Not enough money!");
}
money = money.minus(amount);
}
private void receiveMoney(Money amount) {
money = money.plus(amount);
}
}
|
Optional<String> purchasesToShow =
purchases.stream()
.map(p -> p.getName() + " - $" + p.getSalePrice().getAmount())
.reduce((p1, p2) -> p1 + ", " + p2);
if (purchasesToShow.isPresent()) {
LOGGER.info(name + " bought: " + purchasesToShow.get());
} else {
LOGGER.info(name + " didn't bought anything");
}
| 790
| 129
| 919
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDaoImpl.java
|
CustomerDaoImpl
|
update
|
class CustomerDaoImpl implements CustomerDao {
private final DataSource dataSource;
public CustomerDaoImpl(final DataSource userDataSource) {
this.dataSource = userDataSource;
}
@Override
public Optional<Customer> findByName(String name) throws SQLException {
var sql = "select * from CUSTOMERS where name = ?;";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, name);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
return Optional.of(
Customer.builder()
.name(rs.getString("name"))
.money(Money.of(USD, rs.getBigDecimal("money")))
.customerDao(this)
.build());
} else {
return Optional.empty();
}
}
}
@Override
public void update(Customer customer) throws SQLException {<FILL_FUNCTION_BODY>}
@Override
public void save(Customer customer) throws SQLException {
var sql = "insert into CUSTOMERS (name, money) values (?, ?)";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, customer.getName());
preparedStatement.setBigDecimal(2, customer.getMoney().getAmount());
preparedStatement.executeUpdate();
}
}
@Override
public void addProduct(Product product, Customer customer) throws SQLException {
var sql = "insert into PURCHASES (product_name, customer_name) values (?,?)";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, product.getName());
preparedStatement.setString(2, customer.getName());
preparedStatement.executeUpdate();
}
}
@Override
public void deleteProduct(Product product, Customer customer) throws SQLException {
var sql = "delete from PURCHASES where product_name = ? and customer_name = ?";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, product.getName());
preparedStatement.setString(2, customer.getName());
preparedStatement.executeUpdate();
}
}
}
|
var sql = "update CUSTOMERS set money = ? where name = ?;";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setBigDecimal(1, customer.getMoney().getAmount());
preparedStatement.setString(2, customer.getName());
preparedStatement.executeUpdate();
}
| 626
| 97
| 723
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/domain-model/src/main/java/com/iluwatar/domainmodel/Product.java
|
Product
|
save
|
class Product {
private static final int DAYS_UNTIL_EXPIRATION_WHEN_DISCOUNT_ACTIVE = 4;
private static final double DISCOUNT_RATE = 0.2;
@NonNull private final ProductDao productDao;
@NonNull private String name;
@NonNull private Money price;
@NonNull private LocalDate expirationDate;
/**
* Save product or update if product already exist.
*/
public void save() {<FILL_FUNCTION_BODY>}
/**
* Calculate sale price of product with discount.
*/
public Money getSalePrice() {
return price.minus(calculateDiscount());
}
private Money calculateDiscount() {
if (ChronoUnit.DAYS.between(LocalDate.now(), expirationDate)
< DAYS_UNTIL_EXPIRATION_WHEN_DISCOUNT_ACTIVE) {
return price.multipliedBy(DISCOUNT_RATE, RoundingMode.DOWN);
}
return Money.zero(USD);
}
}
|
try {
Optional<Product> product = productDao.findByName(name);
if (product.isPresent()) {
productDao.update(this);
} else {
productDao.save(this);
}
} catch (SQLException ex) {
LOGGER.error(ex.getMessage());
}
| 276
| 87
| 363
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDaoImpl.java
|
ProductDaoImpl
|
save
|
class ProductDaoImpl implements ProductDao {
private final DataSource dataSource;
public ProductDaoImpl(final DataSource userDataSource) {
this.dataSource = userDataSource;
}
@Override
public Optional<Product> findByName(String name) throws SQLException {
var sql = "select * from PRODUCTS where name = ?;";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, name);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
return Optional.of(
Product.builder()
.name(rs.getString("name"))
.price(Money.of(USD, rs.getBigDecimal("price")))
.expirationDate(rs.getDate("expiration_date").toLocalDate())
.productDao(this)
.build());
} else {
return Optional.empty();
}
}
}
@Override
public void save(Product product) throws SQLException {<FILL_FUNCTION_BODY>}
@Override
public void update(Product product) throws SQLException {
var sql = "update PRODUCTS set price = ?, expiration_date = ? where name = ?;";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setBigDecimal(1, product.getPrice().getAmount());
preparedStatement.setDate(2, Date.valueOf(product.getExpirationDate()));
preparedStatement.setString(3, product.getName());
preparedStatement.executeUpdate();
}
}
}
|
var sql = "insert into PRODUCTS (name, price, expiration_date) values (?, ?, ?)";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, product.getName());
preparedStatement.setBigDecimal(2, product.getPrice().getAmount());
preparedStatement.setDate(3, Date.valueOf(product.getExpirationDate()));
preparedStatement.executeUpdate();
}
| 437
| 127
| 564
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java
|
App
|
printBlackPixelCoordinate
|
class App {
/**
* Program main entry point.
*
* @param args runtime arguments
*/
public static void main(String[] args) {
final var scene = new Scene();
var drawPixels1 = List.of(
new MutablePair<>(1, 1),
new MutablePair<>(5, 6),
new MutablePair<>(3, 2)
);
scene.draw(drawPixels1);
var buffer1 = scene.getBuffer();
printBlackPixelCoordinate(buffer1);
var drawPixels2 = List.of(
new MutablePair<>(3, 7),
new MutablePair<>(6, 1)
);
scene.draw(drawPixels2);
var buffer2 = scene.getBuffer();
printBlackPixelCoordinate(buffer2);
}
private static void printBlackPixelCoordinate(Buffer buffer) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder log = new StringBuilder("Black Pixels: ");
var pixels = buffer.getPixels();
for (var i = 0; i < pixels.length; ++i) {
if (pixels[i] == Pixel.BLACK) {
var y = i / FrameBuffer.WIDTH;
var x = i % FrameBuffer.WIDTH;
log.append(" (").append(x).append(", ").append(y).append(")");
}
}
LOGGER.info(log.toString());
| 254
| 136
| 390
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java
|
Scene
|
swap
|
class Scene {
private final Buffer[] frameBuffers;
private int current;
private int next;
/**
* Constructor of Scene.
*/
public Scene() {
frameBuffers = new FrameBuffer[2];
frameBuffers[0] = new FrameBuffer();
frameBuffers[1] = new FrameBuffer();
current = 0;
next = 1;
}
/**
* Draw the next frame.
*
* @param coordinateList list of pixels of which the color should be black
*/
public void draw(List<? extends Pair<Integer, Integer>> coordinateList) {
LOGGER.info("Start drawing next frame");
LOGGER.info("Current buffer: " + current + " Next buffer: " + next);
frameBuffers[next].clearAll();
coordinateList.forEach(coordinate -> {
var x = coordinate.getKey();
var y = coordinate.getValue();
frameBuffers[next].draw(x, y);
});
LOGGER.info("Swap current and next buffer");
swap();
LOGGER.info("Finish swapping");
LOGGER.info("Current buffer: " + current + " Next buffer: " + next);
}
public Buffer getBuffer() {
LOGGER.info("Get current buffer: " + current);
return frameBuffers[current];
}
private void swap() {<FILL_FUNCTION_BODY>}
}
|
current = current ^ next;
next = current ^ next;
current = current ^ next;
| 371
| 27
| 398
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
final var inventory = new Inventory(1000);
var executorService = Executors.newFixedThreadPool(3);
IntStream.range(0, 3).<Runnable>mapToObj(i -> () -> {
while (inventory.addItem(new Item())) {
LOGGER.info("Adding another item");
}
}).forEach(executorService::execute);
executorService.shutdown();
try {
executorService.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOGGER.error("Error waiting for ExecutorService shutdown");
Thread.currentThread().interrupt();
}
| 56
| 179
| 235
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.