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(... |
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.ofStr... | 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 d... |
// 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(l... | 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(Asyn... |
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)) {
... | 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)... |
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!... | 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 FlyingEnchan... | 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(... | 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... | 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(Stri... |
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 LIT... |
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.fo... | 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... |
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.p... | 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) {
... |
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) {
... |
// 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 (isDbMon... | 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 A... |
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(userAcco... | 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 ... |
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... |
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;
}
... |
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 appIn... | 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_FUNC... |
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 quickServiceCircuitBreak... | 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 t... |
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
... | 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
*/
pub... |
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 r... | 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 ser... |
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 ... |
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 w... |
/*
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));
/*
... | 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>}
/**
* ... |
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 groupingByCategoryImperati... | 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 ... | 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<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<Ca... | 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 t... |
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(queriesA... | 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) {
retur... |
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();
... | 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 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.
*/
publi... |
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... |
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new Shippi... | 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
... |
//rest is successful
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException())... | 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
... |
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 EmployeeHand... | 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
pr... |
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 DatabaseUnavailabl... | 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
... |
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 Comma... | 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 cr... |
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 a... |
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
... | 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 Hashtabl... |
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 (U... | 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 D... |
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,ja... |
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... |
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 w... | 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,ja... |
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 receiv... |
//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,ja... |
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<>(o... |
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) {<FI... |
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.ex... |
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... |
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(... |
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,ja... |
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... |
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... |
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.get... | 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>'... |
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... |
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... | 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 = ... | 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", "Tou... | 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, "... | 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 w... |
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.cre... |
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("ti... | 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);
LO... | 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("D... | 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);
... | 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;
}
... |
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(f... |
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, "... | 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 dat... |
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.OR... | 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 Op... |
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... | 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) {
... |
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 : {... |
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.
*/
... |
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 ... |
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 compo... |
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");
... | 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()... |
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(cus... |
// 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 custome... | 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... | 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_PRI... | 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(... | 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 coun... | 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;
}
... |
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.lin... | 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() {<FIL... |
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 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()
... | 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... |
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.... | 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 wher... |
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());
... | 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 pr... |
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 nam... |
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.getPr... | 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.... |
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).a... | 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;
}
/**... |
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);
executorSe... | 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.