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/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java | Inventory | addItem | class Inventory {
private final int inventorySize;
private final List<Item> items;
private final Lock lock;
/**
* Constructor.
*/
public Inventory(int inventorySize) {
this.inventorySize = inventorySize;
this.items = new ArrayList<>(inventorySize);
this.lock = new ReentrantLock();
}
/... |
if (items.size() < inventorySize) {
lock.lock();
try {
if (items.size() < inventorySize) {
items.add(item);
var thread = Thread.currentThread();
LOGGER.info("{}: items.size()={}, inventorySize={}", thread, items.size(), inventorySize);
return true;
... | 202 | 117 | 319 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
// initialize game objects and print their status
var objects = List.of(
new FlamingAsteroid(0, 0, 5, 5),
new SpaceStationMir(1, 1, 2, 2),
new Meteoroid(10, 10, 15, 15),
new SpaceStationIss(12, 12, 14, 14)
);
objects.forEach(o -> LOGGER.info(o.toString()));
LOGGER.in... | 56 | 244 | 300 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java | GameObject | toString | class GameObject extends Rectangle {
private boolean damaged;
private boolean onFire;
public GameObject(int left, int top, int right, int bottom) {
super(left, top, right, bottom);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public abstract void collision(GameObject gameObject);
... |
return String.format("%s at %s damaged=%b onFire=%b", this.getClass().getSimpleName(),
super.toString(), isDamaged(), isOnFire());
| 165 | 48 | 213 | <methods>public non-sealed void <init>() ,public java.lang.String toString() <variables>private final non-sealed int bottom,private final non-sealed int left,private final non-sealed int right,private final non-sealed int top |
iluwatar_java-design-patterns | java-design-patterns/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java | Rectangle | intersectsWith | class Rectangle {
private final int left;
private final int top;
private final int right;
private final int bottom;
boolean intersectsWith(Rectangle r) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return String.format("[%d,%d,%d,%d]", getLeft(), getTop(), getRight(), getBottom());
... |
return !(r.getLeft() > getRight() || r.getRight() < getLeft() || r.getTop() > getBottom() || r
.getBottom() < getTop());
| 111 | 49 | 160 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java | SpaceStationMir | collisionResolve | class SpaceStationMir extends GameObject {
public SpaceStationMir(int left, int top, int right, int bottom) {
super(left, top, right, bottom);
}
@Override
public void collision(GameObject gameObject) {
gameObject.collisionResolve(this);
}
@Override
public void collisionResolve(FlamingAsteroid a... |
LOGGER.info(AppConstants.HITS, " {} is damaged!", iss.getClass().getSimpleName(),
this.getClass().getSimpleName(), this.getClass().getSimpleName());
setDamaged(true);
| 392 | 61 | 453 | <methods>public void <init>(int, int, int, int) ,public abstract void collision(com.iluwatar.doubledispatch.GameObject) ,public abstract void collisionResolve(com.iluwatar.doubledispatch.FlamingAsteroid) ,public abstract void collisionResolve(com.iluwatar.doubledispatch.Meteoroid) ,public abstract void collisionResolve... |
iluwatar_java-design-patterns | java-design-patterns/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumInvocationHandler.java | AlbumInvocationHandler | invoke | class AlbumInvocationHandler implements InvocationHandler {
private TinyRestClient restClient;
/**
* Class constructor. It instantiates a TinyRestClient object.
*
* @param baseUrl Root url for endpoints.
* @param httpClient Handle the http communication.
*/
public AlbumInvocationHandler(String... |
LOGGER.info("===== Calling the method {}.{}()",
method.getDeclaringClass().getSimpleName(), method.getName());
return restClient.send(method, args);
| 158 | 52 | 210 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/App.java | App | callMethods | class App {
static final String REST_API_URL = "https://jsonplaceholder.typicode.com";
private String baseUrl;
private HttpClient httpClient;
private AlbumService albumServiceProxy;
/**
* Class constructor.
*
* @param baseUrl Root url for endpoints.
* @param httpClient Handle the http commun... |
int albumId = 17;
int userId = 3;
var albums = albumServiceProxy.readAlbums();
albums.forEach(album -> LOGGER.info("{}", album));
var album = albumServiceProxy.readAlbum(albumId);
LOGGER.info("{}", album);
var newAlbum = albumServiceProxy.createAlbum(Album.builder()
.title("Big W... | 404 | 222 | 626 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/JsonUtil.java | JsonUtil | jsonToObject | class JsonUtil {
private static ObjectMapper objectMapper = new ObjectMapper();
private JsonUtil() {
}
/**
* Convert an object to a Json string representation.
*
* @param object Object to convert.
* @param <T> Object's class.
* @return Json string.
*/
public static <T> String objectToJ... |
try {
return objectMapper.readValue(json, clazz);
} catch (IOException e) {
LOGGER.error("Cannot convert the Json " + json + " to class " + clazz.getName() + ".", e);
return null;
}
| 476 | 68 | 544 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/TinyRestClient.java | TinyRestClient | getResponse | class TinyRestClient {
private static Map<Method, Annotation> httpAnnotationByMethod = new HashMap<>();
private String baseUrl;
private HttpClient httpClient;
/**
* Class constructor.
*
* @param baseUrl Root url for endpoints.
* @param httpClient Handle the http communication.
*/
public T... |
var rawData = httpResponse.body();
Type returnType = null;
try {
returnType = method.getGenericReturnType();
} catch (Exception e) {
LOGGER.error("Cannot get the generic return type of the method " + method.getName() + "()");
return null;
}
if (returnType instanceof Parameteri... | 1,183 | 184 | 1,367 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/embedded-value/src/main/java/com/iluwatar/embedded/value/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args.
* @throws Exception if any error occurs.
*
*/
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
} |
final var dataSource = new DataSource();
// Orders to insert into database
final var order1 = new Order("JBL headphone", "Ram",
new ShippingAddress("Bangalore", "Karnataka", "560040"));
final var order2 = new Order("MacBook Pro", "Manjunath",
new ShippingAddress("Bangalore", "Karnatak... | 75 | 669 | 744 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSource.java | DataSource | removeOrder | class DataSource implements DataSourceInterface {
private Connection conn;
// Statements are objects which are used to execute queries which will not be repeated.
private Statement getschema;
private Statement deleteschema;
private Statement queryOrders;
// PreparedStatements are used to execute queries w... |
try {
conn.setAutoCommit(false);
removeorder.setInt(1, id);
if (removeorder.executeUpdate() == 1) {
LOGGER.info("Order with id " + id + " successfully removed");
} else {
LOGGER.info("Order with id " + id + " unavailable.");
}
} catch (Exception e) {
LOGGER.e... | 1,522 | 143 | 1,665 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
var kingJoffrey = new KingJoffrey();
var kingsHand = new KingsHand();
kingsHand.registerObserver(kingJoffrey, Event.TRAITOR_DETECTED);
kingsHand.registerObserver(kingJoffrey, Event.STARK_SIGHTED);
kingsHand.registerObserver(kingJoffrey, Event.WARSHIPS_APPROACHING);
kingsHand.registerObserver(... | 56 | 369 | 425 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java | EventEmitter | registerObserver | class EventEmitter {
private final Map<Event, List<EventObserver>> observerLists;
public EventEmitter() {
observerLists = new HashMap<>();
}
public EventEmitter(EventObserver obs, Event e) {
this();
registerObserver(obs, e);
}
/**
* Registers observer for specific event in the related list... |
if (!observerLists.containsKey(e)) {
observerLists.put(e, new LinkedList<>());
}
if (!observerLists.get(e).contains(obs)) {
observerLists.get(e).add(obs);
}
| 239 | 71 | 310 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java | Scout | timePasses | class Scout extends EventEmitter {
public Scout() {
}
public Scout(EventObserver obs, Event e) {
super(obs, e);
}
@Override
public void timePasses(Weekday day) {<FILL_FUNCTION_BODY>}
} |
if (day == Weekday.TUESDAY) {
notifyObservers(Event.WARSHIPS_APPROACHING);
}
if (day == Weekday.WEDNESDAY) {
notifyObservers(Event.WHITE_WALKERS_SIGHTED);
}
| 79 | 79 | 158 | <methods>public void <init>() ,public void <init>(com.iluwatar.event.aggregator.EventObserver, com.iluwatar.event.aggregator.Event) ,public final void registerObserver(com.iluwatar.event.aggregator.EventObserver, com.iluwatar.event.aggregator.Event) ,public abstract void timePasses(com.iluwatar.event.aggregator.Weekday... |
iluwatar_java-design-patterns | java-design-patterns/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java | App | quickRun | class App {
public static final String PROP_FILE_NAME = "config.properties";
boolean interactiveMode = false;
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var app = new App();
app.setUp();
app.run();
}
/**
* App can r... |
var eventManager = new EventManager();
try {
// Create an Asynchronous event.
var asyncEventId = eventManager.createAsync(60);
LOGGER.info("Async Event [{}] has been created.", asyncEventId);
eventManager.start(asyncEventId);
LOGGER.info("Async Event [{}] has been started.", asyn... | 1,292 | 303 | 1,595 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java | AsyncEvent | status | class AsyncEvent implements Event, Runnable {
private final int eventId;
private final int eventTime;
@Getter
private final boolean synchronous;
private Thread thread;
private boolean isComplete = false;
private ThreadCompleteListener eventListener;
@Override
public void start() {
thread = new T... |
if (!isComplete) {
LOGGER.info("[{}] is not done.", eventId);
} else {
LOGGER.info("[{}] is done.", eventId);
}
| 376 | 52 | 428 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java | EventManager | generateId | class EventManager implements ThreadCompleteListener {
public static final int MAX_RUNNING_EVENTS = 1000;
// Just don't wanna have too many running events. :)
public static final int MIN_ID = 1;
public static final int MAX_ID = MAX_RUNNING_EVENTS;
public static final int MAX_EVENT_TIME = 1800; // in seconds ... |
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
var randomNum = rand.nextInt((MAX_ID - MIN_ID) + 1) + MIN_ID;
while (eventPool.containsKey(randomNum)) {
randomNum = rand.nextInt((MAX_ID - MIN_ID) + 1) + MIN_ID;
}
return randomNum;
| 1,597 | 106 | 1,703 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java | App | main | class App {
/**
* Once the {@link EventDispatcher} is initialised, handlers related to specific events have to be
* made known to the dispatcher by registering them. In this case the {@link UserCreatedEvent} is
* bound to the UserCreatedEventHandler, whilst the {@link UserUpdatedEvent} is bound to the
* ... |
var dispatcher = new EventDispatcher();
dispatcher.registerHandler(UserCreatedEvent.class, new UserCreatedEventHandler());
dispatcher.registerHandler(UserUpdatedEvent.class, new UserUpdatedEventHandler());
var user = new User("iluwatar");
dispatcher.dispatch(new UserCreatedEvent(user));
dispa... | 180 | 97 | 277 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java | EventDispatcher | dispatch | class EventDispatcher {
private final Map<Class<? extends Event>, Handler<? extends Event>> handlers;
public EventDispatcher() {
handlers = new HashMap<>();
}
/**
* Links an {@link Event} to a specific {@link Handler}.
*
* @param eventType The {@link Event} to be registered
* @param handler ... |
var handler = (Handler<E>) handlers.get(event.getClass());
if (handler != null) {
handler.onEvent(event);
}
| 249 | 46 | 295 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/event-queue/src/main/java/com/iluwatar/event/queue/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
* @throws IOException when there is a problem with the audio file loading
* @throws UnsupportedAudioFileException when the loaded audio file is unsupported
*/
public static void main(String[] args) throws U... |
var audio = Audio.getInstance();
audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f);
audio.playSound(audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f);
LOGGER.info("Press Enter key to stop the program...");
try (var br = new BufferedReader(new InputStreamReader(System.i... | 105 | 136 | 241 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java | Audio | update | class Audio {
private static final Audio INSTANCE = new Audio();
private static final int MAX_PENDING = 16;
private int headIndex;
private int tailIndex;
private volatile Thread updateThread = null;
private final PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING];
// Visible only for testing ... |
// If there are no pending requests, do nothing.
if (headIndex == tailIndex) {
return;
}
try {
var audioStream = getPendingAudio()[headIndex].getStream();
headIndex++;
var clip = AudioSystem.getClip();
clip.open(audioStream);
clip.start();
} catch (LineUnavailabl... | 887 | 188 | 1,075 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java | App | main | class App {
/**
* The constant ACCOUNT OF DAENERYS.
*/
public static final int ACCOUNT_OF_DAENERYS = 1;
/**
* The constant ACCOUNT OF JON.
*/
public static final int ACCOUNT_OF_JON = 2;
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void ... |
var eventProcessor = new DomainEventProcessor(new JsonFileJournal());
LOGGER.info("Running the system first time............");
eventProcessor.reset();
LOGGER.info("Creating the accounts............");
eventProcessor.process(new AccountCreateEvent(
0, new Date().getTime(), ACCOUNT_OF_DA... | 132 | 514 | 646 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java | Account | toString | class Account {
private final int accountNo;
private final String owner;
private BigDecimal money = BigDecimal.ZERO;
private static final String MSG =
"Some external api for only realtime execution could be called here.";
/**
* Copy account.
*
* @return the account
*/
public Account cop... |
return "Account{"
+ "accountNo=" + accountNo
+ ", owner='" + owner + '\''
+ ", money=" + money
+ '}';
| 717 | 47 | 764 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java | AccountCreateEvent | process | class AccountCreateEvent extends DomainEvent {
private final int accountNo;
private final String owner;
/**
* Instantiates a new Account created event.
*
* @param sequenceId the sequence id
* @param createdTime the created time
* @param accountNo the account no
* @param owner the owne... |
var account = AccountAggregate.getAccount(accountNo);
if (account != null) {
throw new RuntimeException("Account already exists");
}
account = new Account(accountNo, owner);
account.handleEvent(this);
| 210 | 63 | 273 | <methods>public non-sealed void <init>() ,public abstract void process() <variables>private final non-sealed long createdTime,private final non-sealed java.lang.String eventClassName,private boolean realTime,private final non-sealed long sequenceId |
iluwatar_java-design-patterns | java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java | MoneyDepositEvent | process | class MoneyDepositEvent extends DomainEvent {
private final BigDecimal money;
private final int accountNo;
/**
* Instantiates a new Money deposit event.
*
* @param sequenceId the sequence id
* @param createdTime the created time
* @param accountNo the account no
* @param money the mon... |
var account = Optional.ofNullable(AccountAggregate.getAccount(accountNo))
.orElseThrow(() -> new RuntimeException("Account not found"));
account.handleEvent(this);
| 221 | 50 | 271 | <methods>public non-sealed void <init>() ,public abstract void process() <variables>private final non-sealed long createdTime,private final non-sealed java.lang.String eventClassName,private boolean realTime,private final non-sealed long sequenceId |
iluwatar_java-design-patterns | java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java | MoneyTransferEvent | process | class MoneyTransferEvent extends DomainEvent {
private final BigDecimal money;
private final int accountNoFrom;
private final int accountNoTo;
/**
* Instantiates a new Money transfer event.
*
* @param sequenceId the sequence id
* @param createdTime the created time
* @param money t... |
var accountFrom = Optional.ofNullable(AccountAggregate.getAccount(accountNoFrom))
.orElseThrow(() -> new RuntimeException("Account not found " + accountNoFrom));
var accountTo = Optional.ofNullable(AccountAggregate.getAccount(accountNoTo))
.orElseThrow(() -> new RuntimeException("Account not fo... | 274 | 119 | 393 | <methods>public non-sealed void <init>() ,public abstract void process() <variables>private final non-sealed long createdTime,private final non-sealed java.lang.String eventClassName,private boolean realTime,private final non-sealed long sequenceId |
iluwatar_java-design-patterns | java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java | DomainEventProcessor | recover | class DomainEventProcessor {
private final EventJournal eventJournal;
public DomainEventProcessor(EventJournal eventJournal) {
this.eventJournal = eventJournal;
}
/**
* Process.
*
* @param domainEvent the domain event
*/
public void process(DomainEvent domainEvent) {
domainEvent.process... |
DomainEvent domainEvent;
while ((domainEvent = eventJournal.readNext()) != null) {
domainEvent.process();
}
| 174 | 40 | 214 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java | JsonFileJournal | write | class JsonFileJournal extends EventJournal {
private final List<String> events = new ArrayList<>();
private int index = 0;
/**
* Instantiates a new Json file journal.
*/
public JsonFileJournal() {
file = new File("Journal.json");
if (file.exists()) {
try (var input = new BufferedReader(
... |
var mapper = new ObjectMapper();
try (var output = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8))) {
var eventString = mapper.writeValueAsString(domainEvent);
output.write(eventString + "\r\n");
} catch (IOException e) {
throw... | 538 | 101 | 639 | <methods>public non-sealed void <init>() <variables>java.io.File file |
iluwatar_java-design-patterns | java-design-patterns/execute-around/src/main/java/com/iluwatar/execute/around/App.java | App | main | class App {
/**
* Program entry point.
*/
public static void main(String[] args) throws IOException {<FILL_FUNCTION_BODY>}
} |
// create the file writer and execute the custom action
FileWriterAction writeHello = writer -> {
writer.write("Gandalf was here");
};
new SimpleFileWriter("testfile.txt", writeHello);
// print the file contents
try (var scanner = new Scanner(new File("testfile.txt"))) {
while (sc... | 46 | 119 | 165 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/extension-objects/src/main/java/App.java | App | checkExtensionsForUnit | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
//Create 3 different units
var soldierUnit = new SoldierUnit("SoldierUnit1");
var sergeantUnit = new SergeantUnit("SergeantUnit1");
var commanderUnit = new CommanderUnit... |
final var logger = LoggerFactory.getLogger(App.class);
var name = unit.getName();
Function<String, Runnable> func = e -> () -> logger.info("{} without {}", name, e);
var extension = "SoldierExtension";
Optional.ofNullable(unit.getUnitExtension(extension))
.map(e -> (SoldierExtension) e)
... | 184 | 254 | 438 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/extension-objects/src/main/java/units/CommanderUnit.java | CommanderUnit | getUnitExtension | class CommanderUnit extends Unit {
public CommanderUnit(String name) {
super(name);
}
@Override
public UnitExtension getUnitExtension(String extensionName) {<FILL_FUNCTION_BODY>}
} |
if (extensionName.equals("CommanderExtension")) {
return Optional.ofNullable(unitExtension).orElseGet(() -> new Commander(this));
}
return super.getUnitExtension(extensionName);
| 62 | 58 | 120 | <methods>public void <init>(java.lang.String) ,public abstractextensions.UnitExtension getUnitExtension(java.lang.String) <variables>private java.lang.String name,protected abstractextensions.UnitExtension unitExtension |
iluwatar_java-design-patterns | java-design-patterns/extension-objects/src/main/java/units/SergeantUnit.java | SergeantUnit | getUnitExtension | class SergeantUnit extends Unit {
public SergeantUnit(String name) {
super(name);
}
@Override
public UnitExtension getUnitExtension(String extensionName) {<FILL_FUNCTION_BODY>}
} |
if (extensionName.equals("SergeantExtension")) {
return Optional.ofNullable(unitExtension).orElseGet(() -> new Sergeant(this));
}
return super.getUnitExtension(extensionName);
| 62 | 58 | 120 | <methods>public void <init>(java.lang.String) ,public abstractextensions.UnitExtension getUnitExtension(java.lang.String) <variables>private java.lang.String name,protected abstractextensions.UnitExtension unitExtension |
iluwatar_java-design-patterns | java-design-patterns/extension-objects/src/main/java/units/SoldierUnit.java | SoldierUnit | getUnitExtension | class SoldierUnit extends Unit {
public SoldierUnit(String name) {
super(name);
}
@Override
public UnitExtension getUnitExtension(String extensionName) {<FILL_FUNCTION_BODY>}
} |
if (extensionName.equals("SoldierExtension")) {
return Optional.ofNullable(unitExtension).orElseGet(() -> new Soldier(this));
}
return super.getUnitExtension(extensionName);
| 62 | 59 | 121 | <methods>public void <init>(java.lang.String) ,public abstractextensions.UnitExtension getUnitExtension(java.lang.String) <variables>private java.lang.String name,protected abstractextensions.UnitExtension unitExtension |
iluwatar_java-design-patterns | java-design-patterns/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java | DwarvenCartOperator | work | class DwarvenCartOperator extends DwarvenMineWorker {
@Override
public void work() {<FILL_FUNCTION_BODY>}
@Override
public String name() {
return "Dwarf cart operator";
}
} |
LOGGER.info("{} moves gold chunks out of the mine.", name());
| 76 | 24 | 100 | <methods>public non-sealed void <init>() ,public transient void action(com.iluwatar.facade.DwarvenMineWorker.Action[]) ,public void goHome() ,public void goToMine() ,public void goToSleep() ,public abstract java.lang.String name() ,public void wakeUp() ,public abstract void work() <variables> |
iluwatar_java-design-patterns | java-design-patterns/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java | DwarvenMineWorker | action | class DwarvenMineWorker {
public void goToSleep() {
LOGGER.info("{} goes to sleep.", name());
}
public void wakeUp() {
LOGGER.info("{} wakes up.", name());
}
public void goHome() {
LOGGER.info("{} goes home.", name());
}
public void goToMine() {
LOGGER.info("{} goes to t... |
switch (action) {
case GO_TO_SLEEP -> goToSleep();
case WAKE_UP -> wakeUp();
case GO_HOME -> goHome();
case GO_TO_MINE -> goToMine();
case WORK -> work();
default -> LOGGER.info("Undefined action");
}
| 273 | 102 | 375 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/factory-kit/src/main/java/com/iluwatar/factorykit/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
var factory = WeaponFactory.factory(builder -> {
builder.add(WeaponType.SWORD, Sword::new);
builder.add(WeaponType.AXE, Axe::new);
builder.add(WeaponType.SPEAR, Spear::new);
builder.add(WeaponType.BOW, Bow::new);
});
var list = new ArrayList<Weapon>();
list.add(factory.create(We... | 56 | 206 | 262 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/factory-method/src/main/java/com/iluwatar/factory/method/App.java | App | main | class App {
private static final String MANUFACTURED = "{} manufactured {}";
/**
* Program entry point.
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
Blacksmith blacksmith = new OrcBlacksmith();
Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
LOGGER.info(MANUFACTURED, blacksmith, weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
LOGGER.info(MANUFACTURED, blacksmith, weapon);
blacksmith = new ElfBlacksmith();
... | 72 | 198 | 270 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/factory/src/main/java/com/iluwatar/factory/App.java | App | main | class App {
/**
* Program main entry point.
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
LOGGER.info("The alchemist begins his work.");
var coin1 = CoinFactory.getCoin(CoinType.COPPER);
var coin2 = CoinFactory.getCoin(CoinType.GOLD);
LOGGER.info(coin1.getDescription());
LOGGER.info(coin2.getDescription());
| 45 | 87 | 132 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/App.java | App | main | class App {
/**
* Entry point.
*
* <p>Implementation provided has a list of numbers that has to be squared and added. The list can
* be chunked in any way and the "activity function" {@link
* SquareNumberRequest#delayedSquaring(Consumer)} i.e. squaring the number ca be done
* concurrently. The "fan... |
final List<Long> numbers = Arrays.asList(1L, 3L, 4L, 7L, 8L);
LOGGER.info("Numbers to be squared and get sum --> {}", numbers);
final List<SquareNumberRequest> requests =
numbers.stream().map(SquareNumberRequest::new).toList();
var consumer = new Consumer(0L);
// Pass the request and th... | 165 | 187 | 352 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/FanOutFanIn.java | FanOutFanIn | fanOutFanIn | class FanOutFanIn {
/**
* the main fanOutFanIn function or orchestrator function.
* @param requests List of numbers that need to be squared and summed up
* @param consumer Takes in the squared number from {@link SquareNumberRequest} and sums it up
* @return Aggregated sum of all squared numbers.
*/
... |
ExecutorService service = Executors.newFixedThreadPool(requests.size());
// fanning out
List<CompletableFuture<Void>> futures =
requests.stream()
.map(
request ->
CompletableFuture.runAsync(() -> request.delayedSquaring(consumer), service))
... | 134 | 135 | 269 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/SquareNumberRequest.java | SquareNumberRequest | delayedSquaring | class SquareNumberRequest {
private final Long number;
/**
* Squares the number with a little timeout to give impression of long running process that return
* at different times.
* @param consumer callback class that takes the result after the delay.
* */
public void delayedSquaring(final Consumer c... |
var minTimeOut = 5000L;
SecureRandom secureRandom = new SecureRandom();
var randomTimeOut = secureRandom.nextInt(2000);
try {
// this will make the thread sleep from 5-7s.
Thread.sleep(minTimeOut + randomTimeOut);
} catch (InterruptedException e) {
LOGGER.error("Exception while... | 95 | 136 | 231 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java | App | main | class App {
/**
* Block 1 shows the {@link PropertiesFeatureToggleVersion} being run with {@link Properties}
* setting the feature toggle to enabled.
*
* <p>Block 2 shows the {@link PropertiesFeatureToggleVersion} being run with {@link Properties}
* setting the feature toggle to disabled. Notice the d... |
final var properties = new Properties();
properties.put("enhancedWelcome", true);
var service = new PropertiesFeatureToggleVersion(properties);
final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code"));
LOGGER.info(welcomeMessage);
// ------------------------------------... | 316 | 321 | 637 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java | PropertiesFeatureToggleVersion | getWelcomeMessage | class PropertiesFeatureToggleVersion implements Service {
/**
* True if the welcome message to be returned is the enhanced venison or not. For
* this service it will see the value of the boolean that was set in the constructor {@link
* PropertiesFeatureToggleVersion#PropertiesFeatureToggleVersion(Properties... |
if (isEnhanced()) {
return "Welcome " + user + ". You're using the enhanced welcome message.";
}
return "Welcome to the application.";
| 511 | 48 | 559 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java | TieredFeatureToggleVersion | getWelcomeMessage | class TieredFeatureToggleVersion implements Service {
/**
* Generates a welcome message from the passed {@link User}. The resulting message depends on the
* group of the {@link User}. So if the {@link User} is in the {@link UserGroup#paidGroup} then
* the enhanced version of the welcome message will be retu... |
if (UserGroup.isPaid(user)) {
return "You're amazing " + user + ". Thanks for paying for this awesome software.";
}
return "I suppose you can use this software.";
| 306 | 56 | 362 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java | UserGroup | addUserToFreeGroup | class UserGroup {
private static final List<User> freeGroup = new ArrayList<>();
private static final List<User> paidGroup = new ArrayList<>();
/**
* Add the passed {@link User} to the free user group list.
*
* @param user {@link User} to be added to the free group
* @throws IllegalArgumentException... |
if (paidGroup.contains(user)) {
throw new IllegalArgumentException("User already member of paid group.");
} else {
if (!freeGroup.contains(user)) {
freeGroup.add(user);
}
}
| 395 | 61 | 456 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/filterer/src/main/java/com/iluwatar/filterer/App.java | App | filteringSimpleThreats | class App {
public static void main(String[] args) {
filteringSimpleThreats();
filteringSimpleProbableThreats();
}
/**
* Demonstrates how to filter {@link com.iluwatar.filterer.threat.ProbabilisticThreatAwareSystem}
* based on probability property. The @{@link com.iluwatar.filterer.domain.Filterer... |
LOGGER.info("### Filtering ThreatAwareSystem by ThreatType ###");
var rootkit = new SimpleThreat(ThreatType.ROOTKIT, 1, "Simple-Rootkit");
var trojan = new SimpleThreat(ThreatType.TROJAN, 2, "Simple-Trojan");
List<Threat> threats = List.of(rootkit, trojan);
var threatAwareSystem = new SimpleThrea... | 569 | 234 | 803 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbableThreat.java | SimpleProbableThreat | toString | class SimpleProbableThreat extends SimpleThreat implements ProbableThreat {
private final double probability;
public SimpleProbableThreat(final String name, final int id, final ThreatType threatType,
final double probability) {
super(threatType, id, name);
this.probability = ... |
return "SimpleProbableThreat{"
+ "probability=" + probability
+ "} "
+ super.toString();
| 141 | 36 | 177 | <methods>public non-sealed void <init>() ,public int id() ,public java.lang.String name() ,public com.iluwatar.filterer.threat.ThreatType type() <variables>private final non-sealed int id,private final non-sealed java.lang.String name,private final non-sealed com.iluwatar.filterer.threat.ThreatType threatType |
iluwatar_java-design-patterns | java-design-patterns/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java | App | main | class App {
/**
* Program entry point.
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
private static Function<Integer, String> transformToString() {
return integer -> "String[" + integer + "]";
}
private static Predicate<? super Integer> negatives() {
return integer -> integ... |
var integerList = List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68);
prettyPrint("The initial list contains: ", integerList);
var firstFiveNegatives = SimpleFluentIterable
.fromCopyOf(integerList)
.filter(negatives())
.first(3)
.asList();
pret... | 262 | 527 | 789 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java | DecoratingIterator | next | class DecoratingIterator<E> implements Iterator<E> {
protected final Iterator<E> fromIterator;
private E next;
/**
* Creates an iterator that decorates the given iterator.
*/
public DecoratingIterator(Iterator<E> fromIterator) {
this.fromIterator = fromIterator;
}
/**
* Precomputes and save... |
if (next == null) {
return fromIterator.next();
} else {
final var result = next;
next = null;
return result;
}
| 297 | 47 | 344 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java | LazyFluentIterable | map | class LazyFluentIterable<E> implements FluentIterable<E> {
private final Iterable<E> iterable;
/**
* This constructor can be used to implement anonymous subclasses of the LazyFluentIterable.
*/
protected LazyFluentIterable() {
iterable = this;
}
/**
* Filters the contents of Iterable using the... |
return new LazyFluentIterable<>() {
@Override
public Iterator<T> iterator() {
return new DecoratingIterator<>(null) {
final Iterator<E> oldTypeIterator = iterable.iterator();
@Override
public T computeNext() {
if (oldTypeIterator.hasNext()) {
... | 1,472 | 133 | 1,605 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java | SimpleFluentIterable | first | class SimpleFluentIterable<E> implements FluentIterable<E> {
private final Iterable<E> iterable;
/**
* Filters the contents of Iterable using the given predicate, leaving only the ones which satisfy
* the predicate.
*
* @param predicate the condition to test with for the filtering. If the test is nega... |
var iterator = iterator();
var currentCount = 0;
while (iterator.hasNext()) {
iterator.next();
if (currentCount >= count) {
iterator.remove();
}
currentCount++;
}
return this;
| 1,373 | 71 | 1,444 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/flux/src/main/java/com/iluwatar/flux/app/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
// initialize and wire the system
var menuStore = new MenuStore();
Dispatcher.getInstance().registerStore(menuStore);
var contentStore = new ContentStore();
Dispatcher.getInstance().registerStore(contentStore);
var menuView = new MenuView();
menuStore.registerView(menuView);
var conten... | 56 | 164 | 220 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java | Dispatcher | menuItemSelected | class Dispatcher {
private static Dispatcher instance = new Dispatcher();
private final List<Store> stores = new LinkedList<>();
private Dispatcher() {
}
public static Dispatcher getInstance() {
return instance;
}
public void registerStore(Store store) {
stores.add(store);
}
/**
* Men... |
dispatchAction(new MenuAction(menuItem));
if (menuItem == MenuItem.COMPANY) {
dispatchAction(new ContentAction(Content.COMPANY));
} else {
dispatchAction(new ContentAction(Content.PRODUCTS));
}
| 161 | 69 | 230 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java | ContentStore | onAction | class ContentStore extends Store {
private Content content = Content.PRODUCTS;
@Override
public void onAction(Action action) {<FILL_FUNCTION_BODY>}
public Content getContent() {
return content;
}
} |
if (action.getType().equals(ActionType.CONTENT_CHANGED)) {
var contentAction = (ContentAction) action;
content = contentAction.getContent();
notifyChange();
}
| 68 | 55 | 123 | <methods>public non-sealed void <init>() ,public abstract void onAction(com.iluwatar.flux.action.Action) ,public void registerView(com.iluwatar.flux.view.View) <variables>private final List<com.iluwatar.flux.view.View> views |
iluwatar_java-design-patterns | java-design-patterns/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java | MenuStore | onAction | class MenuStore extends Store {
private MenuItem selected = MenuItem.HOME;
@Override
public void onAction(Action action) {<FILL_FUNCTION_BODY>}
public MenuItem getSelected() {
return selected;
}
} |
if (action.getType().equals(ActionType.MENU_ITEM_SELECTED)) {
var menuAction = (MenuAction) action;
selected = menuAction.getMenuItem();
notifyChange();
}
| 68 | 59 | 127 | <methods>public non-sealed void <init>() ,public abstract void onAction(com.iluwatar.flux.action.Action) ,public void registerView(com.iluwatar.flux.view.View) <variables>private final List<com.iluwatar.flux.view.View> views |
iluwatar_java-design-patterns | java-design-patterns/flux/src/main/java/com/iluwatar/flux/view/ContentView.java | ContentView | storeChanged | class ContentView implements View {
private Content content = Content.PRODUCTS;
@Override
public void storeChanged(Store store) {<FILL_FUNCTION_BODY>}
@Override
public void render() {
LOGGER.info(content.toString());
}
} |
var contentStore = (ContentStore) store;
content = contentStore.getContent();
render();
| 77 | 29 | 106 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/flux/src/main/java/com/iluwatar/flux/view/MenuView.java | MenuView | render | class MenuView implements View {
private MenuItem selected = MenuItem.HOME;
@Override
public void storeChanged(Store store) {
var menuStore = (MenuStore) store;
selected = menuStore.getSelected();
render();
}
@Override
public void render() {<FILL_FUNCTION_BODY>}
public void itemClicked(Men... |
for (var item : MenuItem.values()) {
if (selected.equals(item)) {
LOGGER.info("* {}", item);
} else {
LOGGER.info(item.toString());
}
}
| 121 | 61 | 182 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java | AlchemistShop | drinkPotions | class AlchemistShop {
private final List<Potion> topShelf;
private final List<Potion> bottomShelf;
/**
* Constructor.
*/
public AlchemistShop() {
var factory = new PotionFactory();
topShelf = List.of(
factory.createPotion(PotionType.INVISIBILITY),
factory.createPotion(PotionType.... |
LOGGER.info("Drinking top shelf potions");
topShelf.forEach(Potion::drink);
LOGGER.info("Drinking bottom shelf potions");
bottomShelf.forEach(Potion::drink);
| 506 | 61 | 567 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/flyweight/src/main/java/com/iluwatar/flyweight/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
// create the alchemist shop with the potions
var alchemistShop = new AlchemistShop();
// a brave visitor enters the alchemist shop and drinks all the potions
alchemistShop.drinkPotions();
| 56 | 61 | 117 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java | PotionFactory | createPotion | class PotionFactory {
private final Map<PotionType, Potion> potions;
public PotionFactory() {
potions = new EnumMap<>(PotionType.class);
}
Potion createPotion(PotionType type) {<FILL_FUNCTION_BODY>}
} |
var potion = potions.get(type);
if (potion == null) {
switch (type) {
case HEALING -> potion = new HealingPotion();
case HOLY_WATER -> potion = new HolyWaterPotion();
case INVISIBILITY -> potion = new InvisibilityPotion();
case POISON -> potion = new PoisonPotion();... | 90 | 189 | 279 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java | FrontController | getCommand | class FrontController {
public void handleRequest(String request) {
var command = getCommand(request);
command.process();
}
private Command getCommand(String request) {<FILL_FUNCTION_BODY>}
private static Class<?> getCommandClass(String request) {
try {
return Class.forName("com.iluwatar.fr... |
var commandClass = getCommandClass(request);
try {
return (Command) commandClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new ApplicationException(e);
}
| 133 | 57 | 190 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/game-loop/src/main/java/com/iluwatar/gameloop/App.java | App | main | class App {
/**
* Each type of game loop will run for 2 seconds.
*/
private static final int GAME_LOOP_DURATION_TIME = 2000;
/**
* Program entry point.
* @param args runtime arguments
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
try {
LOGGER.info("Start frame-based game loop:");
var frameBasedGameLoop = new FrameBasedGameLoop();
frameBasedGameLoop.run();
Thread.sleep(GAME_LOOP_DURATION_TIME);
frameBasedGameLoop.stop();
LOGGER.info("Stop frame-based game loop.");
LOGGER.info("Start variable-step ... | 98 | 274 | 372 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/game-loop/src/main/java/com/iluwatar/gameloop/FixedStepGameLoop.java | FixedStepGameLoop | processGameLoop | class FixedStepGameLoop extends GameLoop {
/**
* 20 ms per frame = 50 FPS.
*/
private static final long MS_PER_FRAME = 20;
@Override
protected void processGameLoop() {<FILL_FUNCTION_BODY>}
protected void update() {
controller.moveBullet(0.5f * MS_PER_FRAME / 1000);
}
} |
var previousTime = System.currentTimeMillis();
var lag = 0L;
while (isGameRunning()) {
var currentTime = System.currentTimeMillis();
var elapsedTime = currentTime - previousTime;
previousTime = currentTime;
lag += elapsedTime;
processInput();
while (lag >= MS_PER_FRAME... | 114 | 123 | 237 | <methods>public boolean isGameRunning() ,public void run() ,public void stop() <variables>protected final non-sealed com.iluwatar.gameloop.GameController controller,protected final Logger logger,protected volatile com.iluwatar.gameloop.GameStatus status |
iluwatar_java-design-patterns | java-design-patterns/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java | GameLoop | processInput | class GameLoop {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected volatile GameStatus status;
protected final GameController controller;
/**
* Initialize game status to be stopped.
*/
protected GameLoop() {
controller = new GameController();
status = GameSt... |
try {
var lag = new SecureRandom().nextInt(200) + 50;
Thread.sleep(lag);
} catch (InterruptedException e) {
logger.error(e.getMessage());
/* Clean up whatever needs to be handled before interrupting */
Thread.currentThread().interrupt();
}
| 423 | 86 | 509 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/game-loop/src/main/java/com/iluwatar/gameloop/VariableStepGameLoop.java | VariableStepGameLoop | processGameLoop | class VariableStepGameLoop extends GameLoop {
@Override
protected void processGameLoop() {<FILL_FUNCTION_BODY>}
protected void update(Long elapsedTime) {
controller.moveBullet(0.5f * elapsedTime / 1000);
}
} |
var lastFrameTime = System.currentTimeMillis();
while (isGameRunning()) {
processInput();
var currentFrameTime = System.currentTimeMillis();
var elapsedTime = currentFrameTime - lastFrameTime;
update(elapsedTime);
lastFrameTime = currentFrameTime;
render();
}
| 80 | 85 | 165 | <methods>public boolean isGameRunning() ,public void run() ,public void stop() <variables>protected final non-sealed com.iluwatar.gameloop.GameController controller,protected final Logger logger,protected volatile com.iluwatar.gameloop.GameStatus status |
iluwatar_java-design-patterns | java-design-patterns/gateway/src/main/java/com/iluwatar/gateway/App.java | App | main | class App {
/**
* Simulate an application calling external services.
*/
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
} |
GatewayFactory gatewayFactory = new GatewayFactory();
// Register different gateways
gatewayFactory.registerGateway("ServiceA", new ExternalServiceA());
gatewayFactory.registerGateway("ServiceB", new ExternalServiceB());
gatewayFactory.registerGateway("ServiceC", new ExternalServiceC());
// U... | 49 | 211 | 260 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceA.java | ExternalServiceA | execute | class ExternalServiceA implements Gateway {
@Override
public void execute() throws Exception {<FILL_FUNCTION_BODY>}
} |
LOGGER.info("Executing Service A");
// Simulate a time-consuming task
Thread.sleep(1000);
| 37 | 37 | 74 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceB.java | ExternalServiceB | execute | class ExternalServiceB implements Gateway {
@Override
public void execute() throws Exception {<FILL_FUNCTION_BODY>}
} |
LOGGER.info("Executing Service B");
// Simulate a time-consuming task
Thread.sleep(1000);
| 37 | 37 | 74 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceC.java | ExternalServiceC | error | class ExternalServiceC implements Gateway {
@Override
public void execute() throws Exception {
LOGGER.info("Executing Service C");
// Simulate a time-consuming task
Thread.sleep(1000);
}
public void error() throws Exception {<FILL_FUNCTION_BODY>}
} |
// Simulate an exception
throw new RuntimeException("Service C encountered an error");
| 84 | 23 | 107 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java | App | main | class App {
/**
* Example pattern execution.
*
* @param args - command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
var guardedQueue = new GuardedQueue();
var executorService = Executors.newFixedThreadPool(3);
//here we create first thread which is supposed to get from guardedQueue
executorService.execute(guardedQueue::get);
// here we wait two seconds to show that the thread which is trying
// to get from... | 57 | 232 | 289 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java | GuardedQueue | get | class GuardedQueue {
private final Queue<Integer> sourceList;
public GuardedQueue() {
this.sourceList = new LinkedList<>();
}
/**
* Get the last element of the queue is exists.
*
* @return last element of a queue if queue is not empty
*/
public synchronized Integer get() {<FILL_FUNCTION_BODY... |
while (sourceList.isEmpty()) {
try {
LOGGER.info("waiting");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
LOGGER.info("getting");
return sourceList.peek();
| 186 | 75 | 261 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
/**
* ArithmeticSumTask.
*/
static class ArithmeticSumTask implements AsyncTask<Long> {
private final long numberOfElements;
public ArithmeticSum... |
var service = new AsynchronousService(new LinkedBlockingQueue<>());
/*
* A new task to calculate sum is received but as this is main thread, it should not block. So
* it passes it to the asynchronous task layer to compute and proceeds with handling other
* incoming requests. This is particularly... | 472 | 220 | 692 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java | AsynchronousService | execute | class AsynchronousService {
/*
* This represents the queuing layer as well as synchronous layer of the pattern. The thread pool
* contains worker threads which execute the tasks in blocking/synchronous manner. Long running
* tasks should be performed in the background which does not affect the performance of... |
try {
// some small tasks such as validation can be performed here.
task.onPreCall();
} catch (Exception e) {
task.onError(e);
return;
}
service.submit(new FutureTask<T>(task) {
@Override
protected void done() {
super.done();
try {
/*
... | 471 | 235 | 706 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/AsynchronousHealthChecker.java | AsynchronousHealthChecker | shutdown | class AsynchronousHealthChecker {
/** A scheduled executor service used to execute health checks in a separate thread. */
private final ScheduledExecutorService healthCheckExecutor =
Executors.newSingleThreadScheduledExecutor();
private static final String HEALTH_CHECK_TIMEOUT_MESSAGE = "Health check time... |
try {
// Wait a while for existing tasks to terminate
if (awaitTerminationWithTimeout()) {
LOGGER.info("Health check executor did not terminate in time");
// Attempt to cancel currently executing tasks
healthCheckExecutor.shutdownNow();
// Wait again for tasks to respond... | 865 | 201 | 1,066 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/CpuHealthIndicator.java | CpuHealthIndicator | health | class CpuHealthIndicator implements HealthIndicator {
/** The operating system MXBean used to gather CPU health information. */
private OperatingSystemMXBean osBean;
/** Initializes the {@link OperatingSystemMXBean} instance. */
@PostConstruct
public void init() {
this.osBean = ManagementFactory.getOper... |
if (!(osBean instanceof com.sun.management.OperatingSystemMXBean sunOsBean)) {
LOGGER.error("Unsupported operating system MXBean: {}", osBean.getClass().getName());
return Health.unknown()
.withDetail(ERROR_MESSAGE, "Unsupported operating system MXBean")
.build();
}
double... | 638 | 587 | 1,225 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/CustomHealthIndicator.java | CustomHealthIndicator | health | class CustomHealthIndicator implements HealthIndicator {
private final AsynchronousHealthChecker healthChecker;
private final CacheManager cacheManager;
private final HealthCheckRepository healthCheckRepository;
@Value("${health.check.timeout:10}")
private long timeoutInSeconds;
/**
* Perform a health... |
LOGGER.info("Performing health check");
CompletableFuture<Health> healthFuture =
healthChecker.performCheck(this::check, timeoutInSeconds);
try {
return healthFuture.get(timeoutInSeconds, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
... | 515 | 151 | 666 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/DatabaseTransactionHealthIndicator.java | DatabaseTransactionHealthIndicator | health | class DatabaseTransactionHealthIndicator implements HealthIndicator {
/** A repository for performing health checks on the database. */
private final HealthCheckRepository healthCheckRepository;
/** An asynchronous health checker used to execute health checks in a separate thread. */
private final Asynchronou... |
LOGGER.info("Calling performCheck with timeout {}", timeoutInSeconds);
Supplier<Health> dbTransactionCheck =
() -> {
try {
healthCheckRepository.performTestTransaction();
return Health.up().build();
} catch (Exception e) {
LOGGER.error("Database t... | 255 | 192 | 447 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/GarbageCollectionHealthIndicator.java | GarbageCollectionHealthIndicator | health | class GarbageCollectionHealthIndicator implements HealthIndicator {
/**
* The memory usage threshold above which a warning message is included in the health check
* report.
*/
@Value("${memory.usage.threshold:0.8}")
private double memoryUsageThreshold;
/**
* Performs a health check by gathering ga... |
List<GarbageCollectorMXBean> gcBeans = getGarbageCollectorMxBeans();
List<MemoryPoolMXBean> memoryPoolMxBeans = getMemoryPoolMxBeans();
Map<String, Map<String, String>> gcDetails = new HashMap<>();
for (GarbageCollectorMXBean gcBean : gcBeans) {
Map<String, String> collectorDetails = createColle... | 968 | 165 | 1,133 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/HealthCheckRepository.java | HealthCheckRepository | performTestTransaction | class HealthCheckRepository {
private static final String HEALTH_CHECK_OK = "OK";
@PersistenceContext private EntityManager entityManager;
/**
* Checks the health of the database connection by executing a simple query that should always
* return 1 if the connection is healthy.
*
* @return 1 if the ... |
try {
HealthCheck healthCheck = new HealthCheck();
healthCheck.setStatus(HEALTH_CHECK_OK);
entityManager.persist(healthCheck);
entityManager.flush();
HealthCheck retrievedHealthCheck = entityManager.find(HealthCheck.class, healthCheck.getId());
entityManager.remove(retrievedHeal... | 257 | 118 | 375 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/MemoryHealthIndicator.java | MemoryHealthIndicator | checkMemory | class MemoryHealthIndicator implements HealthIndicator {
private final AsynchronousHealthChecker asynchronousHealthChecker;
/** The timeout in seconds for the health check. */
@Value("${health.check.timeout:10}")
private long timeoutInSeconds;
/**
* The memory usage threshold in percentage. If the memor... |
Supplier<Health> memoryCheck =
() -> {
MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heapMemoryUsage = memoryMxBean.getHeapMemoryUsage();
long maxMemory = heapMemoryUsage.getMax();
long usedMemory = heapMemoryUsage.getUsed();
... | 266 | 367 | 633 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/RetryConfig.java | RetryConfig | retryTemplate | class RetryConfig {
/** The backoff period in milliseconds to wait between retry attempts. */
@Value("${retry.backoff.period:2000}")
private long backOffPeriod;
/** The maximum number of retry attempts for health check operations. */
@Value("${retry.max.attempts:3}")
private int maxAttempts;
/**
* C... |
RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(backOffPeriod); // wait 2 seconds between retries
retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
SimpleRetryPolicy retryPolicy = new Simple... | 169 | 141 | 310 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java | App | main | class App {
/**
* Program entry point.
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
var injector = Guice.createInjector(new LotteryTestingModule());
// start new lottery round
var administration = injector.getInstance(LotteryAdministration.class);
administration.resetLottery();
// submit some lottery tickets
var service = injector.getInstance(LotteryService.class);
Samp... | 44 | 120 | 164 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java | ConsoleAdministration | main | class ConsoleAdministration {
/**
* Program entry point.
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
private static void printMainMenu() {
LOGGER.info("");
LOGGER.info("### Lottery Administration Console ###");
LOGGER.info("(1) Show all submitted tickets");
LOGGER.info... |
MongoConnectionPropertiesLoader.load();
var injector = Guice.createInjector(new LotteryModule());
var administration = injector.getInstance(LotteryAdministration.class);
var service = injector.getInstance(LotteryService.class);
SampleData.submitTickets(service, 20);
var consoleAdministration = ... | 180 | 278 | 458 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java | ConsoleAdministrationSrvImpl | performLottery | class ConsoleAdministrationSrvImpl implements ConsoleAdministrationSrv {
private final LotteryAdministration administration;
private final Logger logger;
/**
* Constructor.
*/
public ConsoleAdministrationSrvImpl(LotteryAdministration administration, Logger logger) {
this.administration = administrati... |
var numbers = administration.performLottery();
logger.info("The winning numbers: {}", numbers.getNumbersAsString());
logger.info("Time to reset the database for next round, eh?");
| 221 | 55 | 276 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java | InMemoryBank | transferFunds | class InMemoryBank implements WireTransfers {
private static final Map<String, Integer> accounts = new HashMap<>();
static {
accounts
.put(LotteryConstants.SERVICE_BANK_ACCOUNT, LotteryConstants.SERVICE_BANK_ACCOUNT_BALANCE);
}
@Override
public void setFunds(String bankAccount, int amount) {
... |
if (accounts.getOrDefault(sourceAccount, 0) >= amount) {
accounts.put(sourceAccount, accounts.get(sourceAccount) - amount);
accounts.put(destinationAccount, accounts.get(destinationAccount) + amount);
return true;
} else {
return false;
}
| 194 | 82 | 276 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java | MongoBank | transferFunds | class MongoBank implements WireTransfers {
private static final String DEFAULT_DB = "lotteryDB";
private static final String DEFAULT_ACCOUNTS_COLLECTION = "accounts";
private MongoClient mongoClient;
private MongoDatabase database;
private MongoCollection<Document> accountsCollection;
/**
* Constructo... |
var sourceFunds = getFunds(sourceAccount);
if (sourceFunds < amount) {
return false;
} else {
var destFunds = getFunds(destinationAccount);
setFunds(sourceAccount, sourceFunds - amount);
setFunds(destinationAccount, destFunds + amount);
return true;
}
| 702 | 101 | 803 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java | InMemoryTicketRepository | save | class InMemoryTicketRepository implements LotteryTicketRepository {
private static final Map<LotteryTicketId, LotteryTicket> tickets = new HashMap<>();
@Override
public Optional<LotteryTicket> findById(LotteryTicketId id) {
return Optional.ofNullable(tickets.get(id));
}
@Override
public Optional<Lott... |
var id = new LotteryTicketId();
tickets.put(id, ticket);
return Optional.of(id);
| 184 | 34 | 218 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java | MongoTicketRepository | getNextId | class MongoTicketRepository implements LotteryTicketRepository {
private static final String DEFAULT_DB = "lotteryDB";
private static final String DEFAULT_TICKETS_COLLECTION = "lotteryTickets";
private static final String DEFAULT_COUNTERS_COLLECTION = "counters";
private static final String TICKET_ID = "ticket... |
var find = new Document("_id", TICKET_ID);
var increase = new Document("seq", 1);
var update = new Document("$inc", increase);
var result = countersCollection.findOneAndUpdate(find, update);
return result.getInteger("seq");
| 1,183 | 74 | 1,257 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java | LotteryAdministration | performLottery | class LotteryAdministration {
private final LotteryTicketRepository repository;
private final LotteryEventLog notifications;
private final WireTransfers wireTransfers;
/**
* Constructor.
*/
@Inject
public LotteryAdministration(LotteryTicketRepository repository, LotteryEventLog notifications,
... |
var numbers = LotteryNumbers.createRandom();
var tickets = getAllSubmittedTickets();
for (var id : tickets.keySet()) {
var lotteryTicket = tickets.get(id);
var playerDetails = lotteryTicket.getPlayerDetails();
var playerAccount = playerDetails.getBankAccount();
var result = LotteryU... | 267 | 266 | 533 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java | LotteryNumbers | generateRandomNumbers | class LotteryNumbers {
private final Set<Integer> numbers;
public static final int MIN_NUMBER = 1;
public static final int MAX_NUMBER = 20;
public static final int NUM_NUMBERS = 4;
/**
* Constructor. Creates random lottery numbers.
*/
private LotteryNumbers() {
numbers = new HashSet<>();
ge... |
numbers.clear();
var generator = new RandomNumberGenerator(MIN_NUMBER, MAX_NUMBER);
while (numbers.size() < NUM_NUMBERS) {
var num = generator.nextInt();
numbers.add(num);
}
| 656 | 68 | 724 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java | LotteryService | submitTicket | class LotteryService {
private final LotteryTicketRepository repository;
private final LotteryEventLog notifications;
private final WireTransfers wireTransfers;
/**
* Constructor.
*/
@Inject
public LotteryService(LotteryTicketRepository repository, LotteryEventLog notifications,
... |
var playerDetails = ticket.getPlayerDetails();
var playerAccount = playerDetails.getBankAccount();
var result = wireTransfers.transferFunds(TICKET_PRIZE, playerAccount, SERVICE_BANK_ACCOUNT);
if (!result) {
notifications.ticketSubmitError(playerDetails);
return Optional.empty();
}
v... | 271 | 138 | 409 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java | LotteryTicket | hashCode | class LotteryTicket {
private final LotteryTicketId id;
private final PlayerDetails playerDetails;
private final LotteryNumbers lotteryNumbers;
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (ob... |
final var prime = 31;
var result = 1;
result = prime * result + ((lotteryNumbers == null) ? 0 : lotteryNumbers.hashCode());
result = prime * result + ((playerDetails == null) ? 0 : playerDetails.hashCode());
return result;
| 263 | 76 | 339 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java | LotteryUtils | checkTicketForPrize | class LotteryUtils {
private LotteryUtils() {
}
/**
* Checks if lottery ticket has won.
*/
public static LotteryTicketCheckResult checkTicketForPrize(
LotteryTicketRepository repository,
LotteryTicketId id,
LotteryNumbers winningNumbers
) {<FILL_FUNCTION_BODY>}
} |
var optional = repository.findById(id);
if (optional.isPresent()) {
if (optional.get().getLotteryNumbers().equals(winningNumbers)) {
return new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 1000);
} else {
return new LotteryTicketCheckResult(CheckResult.NO_PRIZE);
}
} el... | 100 | 135 | 235 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java | MongoEventLog | ticketSubmitted | class MongoEventLog implements LotteryEventLog {
private static final String DEFAULT_DB = "lotteryDB";
private static final String DEFAULT_EVENTS_COLLECTION = "events";
private static final String EMAIL = "email";
private static final String PHONE = "phone";
public static final String MESSAGE = "message";
... |
var document = new Document(EMAIL, details.getEmail());
document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount());
document
.put(MESSAGE, "Lottery ticket was submitted and bank account was charged for 3 credits.");
eventsCollection.insertOne(document);
... | 1,065 | 103 | 1,168 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java | StdOutEventLog | prizeError | class StdOutEventLog implements LotteryEventLog {
@Override
public void ticketSubmitted(PlayerDetails details) {
LOGGER.info("Lottery ticket for {} was submitted. Bank account {} was charged for 3 credits.",
details.getEmail(), details.getBankAccount());
}
@Override
public void ticketDidNotWin(P... |
LOGGER.error("Lottery ticket for {} has won! Unfortunately the bank credit transfer of"
+ " {} failed.", details.getEmail(), prizeAmount);
| 289 | 41 | 330 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java | MongoConnectionPropertiesLoader | load | class MongoConnectionPropertiesLoader {
private static final String DEFAULT_HOST = "localhost";
private static final int DEFAULT_PORT = 27017;
/**
* Try to load connection properties from file. Fall back to default connection properties.
*/
public static void load() {<FILL_FUNCTION_BODY>}
} |
var host = DEFAULT_HOST;
var port = DEFAULT_PORT;
var path = System.getProperty("hexagonal.properties.path");
var properties = new Properties();
if (path != null) {
try (var fin = new FileInputStream(path)) {
properties.load(fin);
host = properties.getProperty("mongo-host");
... | 86 | 178 | 264 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java | SampleData | submitTickets | class SampleData {
private static final List<PlayerDetails> PLAYERS;
private static final SecureRandom RANDOM = new SecureRandom();
static {
PLAYERS = List.of(
new PlayerDetails("john@google.com", "312-342", "+3242434242"),
new PlayerDetails("mary@google.com", "234-987", "+23452346"),
... |
for (var i = 0; i < numTickets; i++) {
var randomPlayerDetails = getRandomPlayerDetails();
var lotteryNumbers = LotteryNumbers.createRandom();
var lotteryTicketId = new LotteryTicketId();
var ticket = new LotteryTicket(lotteryTicketId, randomPlayerDetails, lotteryNumbers);
lotteryServ... | 1,568 | 108 | 1,676 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java | ConsoleLottery | main | class ConsoleLottery {
/**
* Program entry point.
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
private static void printMainMenu() {
LOGGER.info("");
LOGGER.info("### Lottery Service Console ###");
LOGGER.info("(1) Query lottery account funds");
LOGGER.info("(2) Add fun... |
MongoConnectionPropertiesLoader.load();
var injector = Guice.createInjector(new LotteryModule());
var service = injector.getInstance(LotteryService.class);
var bank = injector.getInstance(WireTransfers.class);
try (Scanner scanner = new Scanner(System.in)) {
var exit = false;
while (!ex... | 192 | 302 | 494 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java | LotteryConsoleServiceImpl | checkTicket | class LotteryConsoleServiceImpl implements LotteryConsoleService {
private final Logger logger;
/**
* Constructor.
*/
public LotteryConsoleServiceImpl(Logger logger) {
this.logger = logger;
}
@Override
public void checkTicket(LotteryService service, Scanner scanner) {<FILL_FUNCTION_BODY>}
@O... |
logger.info("What is the ID of the lottery ticket?");
var id = readString(scanner);
logger.info("Give the 4 comma separated winning numbers?");
var numbers = readString(scanner);
try {
var winningNumbers = Arrays.stream(numbers.split(","))
.map(Integer::parseInt)
.limit(4)... | 667 | 326 | 993 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/identity-map/src/main/java/com/iluwatar/identitymap/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args.
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
// Dummy Persons
Person person1 = new Person(1, "John", 27304159);
Person person2 = new Person(2, "Thomas", 42273631);
Person person3 = new Person(3, "Arthur", 27489171);
Person person4 = new Person(4, "Finn", 20499078);
Person person5 = new Person(5, "Michael", 40599078);
// Init databas... | 56 | 327 | 383 | <no_super_class> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.