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/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java | App | main | class App {
private App() {
}
/**
* Application entry point
*
* <p>The application under development is a web application. Normally you would probably have a
* backend that is probably implemented in an object-oriented language (e.g. Java) that serves the
* frontend which comprises of a series of... |
try {
var classLoader = App.class.getClassLoader();
var applicationFile = new File(classLoader.getResource("sample-ui/login.html").getPath());
// should work for unix like OS (mac, unix etc...)
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(applicationFile);
... | 174 | 162 | 336 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/parameter-object/src/main/java/com/iluwatar/parameter/object/App.java | App | main | class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
ParameterObject params = ParameterObject.newBuilder()
.withType("sneakers")
.sortBy("brand")
.build();
LOGGER.info(params.toString());
LOGGER.info(new SearchService().search(params));
| 78 | 66 | 144 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java | SearchService | getQuerySummary | class SearchService {
/**
* Below two methods of name `search` is overloaded so that we can send a default value for
* one of the criteria and call the final api. A default SortOrder is sent in the first method
* and a default SortBy is sent in the second method. So two separate method definitions are
* ... |
return String.format("Requesting shoes of type \"%s\" sorted by \"%s\" in \"%sending\" order..",
type,
sortBy,
sortOrder.getValue());
| 326 | 50 | 376 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/partial-response/src/main/java/com/iluwatar/partialresponse/App.java | App | main | class App {
/**
* Method as act client and request to server for video details.
*
* @param args program argument.
*/
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
} |
var videos = Map.of(
1, new Video(1, "Avatar", 178, "epic science fiction film",
"James Cameron", "English"),
2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|",
"Hideaki Anno", "Japanese"),
3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi",
... | 66 | 336 | 402 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java | FieldJsonMapper | getString | class FieldJsonMapper {
/**
* Gets json of required fields from video.
*
* @param video object containing video information
* @param fields fields information to get
* @return json of required fields from video
*/
public String toJson(Video video, String[] fields) throws Exception {
var json... |
declaredField.setAccessible(true);
var value = declaredField.get(video);
if (declaredField.get(video) instanceof Integer) {
return "\"" + declaredField.getName() + "\"" + ": " + value;
}
return "\"" + declaredField.getName() + "\"" + ": " + "\"" + value.toString() + "\"";
| 226 | 96 | 322 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/pipeline/src/main/java/com/iluwatar/pipeline/App.java | App | main | class App {
/**
* Specify the initial input type for the first stage handler and the expected output type of the
* last stage handler as type parameters for Pipeline. Use the fluent builder by calling
* addHandler to add more stage handlers on the pipeline.
*/
public static void main(String[] args) {<FI... |
/*
Suppose we wanted to pass through a String to a series of filtering stages and convert it
as a char array on the last stage.
- Stage handler 1 (pipe): Removing the alphabets, accepts a String input and returns the
processed String output. This will be used by the next handler as its inp... | 92 | 319 | 411 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java | ConvertToCharArrayHandler | process | class ConvertToCharArrayHandler implements Handler<String, char[]> {
private static final Logger LOGGER = LoggerFactory.getLogger(ConvertToCharArrayHandler.class);
@Override
public char[] process(String input) {<FILL_FUNCTION_BODY>}
} |
var characters = input.toCharArray();
var string = Arrays.toString(characters);
LOGGER.info(
String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s",
ConvertToCharArrayHandler.class, input, String.class, string, Character[].class)
);
return charact... | 73 | 97 | 170 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java | RemoveAlphabetsHandler | process | class RemoveAlphabetsHandler implements Handler<String, String> {
private static final Logger LOGGER = LoggerFactory.getLogger(RemoveAlphabetsHandler.class);
@Override
public String process(String input) {<FILL_FUNCTION_BODY>}
} |
var inputWithoutAlphabets = new StringBuilder();
var isAlphabetic = (IntPredicate) Character::isAlphabetic;
input.chars()
.filter(isAlphabetic.negate())
.mapToObj(x -> (char) x)
.forEachOrdered(inputWithoutAlphabets::append);
var inputWithoutAlphabetsStr = inputWithoutAlphabets... | 73 | 201 | 274 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java | RemoveDigitsHandler | process | class RemoveDigitsHandler implements Handler<String, String> {
private static final Logger LOGGER = LoggerFactory.getLogger(RemoveDigitsHandler.class);
@Override
public String process(String input) {<FILL_FUNCTION_BODY>}
} |
var inputWithoutDigits = new StringBuilder();
var isDigit = (IntPredicate) Character::isDigit;
input.chars()
.filter(isDigit.negate())
.mapToObj(x -> (char) x)
.forEachOrdered(inputWithoutDigits::append);
var inputWithoutDigitsStr = inputWithoutDigits.toString();
LOGGER.inf... | 69 | 179 | 248 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
var queue = new SimpleMessageQueue(10000);
final var producer = new Producer("PRODUCER_1", queue);
final var consumer = new Consumer("CONSUMER_1", queue);
new Thread(consumer::consume).start();
new Thread(() -> {
producer.send("hand shake");
producer.send("some very important informa... | 56 | 122 | 178 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java | Consumer | consume | class Consumer {
private final MqSubscribePoint queue;
private final String name;
public Consumer(String name, MqSubscribePoint queue) {
this.name = name;
this.queue = queue;
}
/**
* Consume message.
*/
public void consume() {<FILL_FUNCTION_BODY>}
} |
while (true) {
try {
var msg = queue.take();
if (Message.POISON_PILL.equals(msg)) {
LOGGER.info("Consumer {} receive request to terminate.", name);
break;
}
var sender = msg.getHeader(Headers.SENDER);
var body = msg.getBody();
LOGGER.info("M... | 96 | 158 | 254 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java | Producer | send | class Producer {
private final MqPublishPoint queue;
private final String name;
private boolean isStopped;
/**
* Constructor.
*/
public Producer(String name, MqPublishPoint queue) {
this.name = name;
this.queue = queue;
this.isStopped = false;
}
/**
* Send message to queue.
*/
... |
if (isStopped) {
throw new IllegalStateException(String.format(
"Producer %s was stopped and fail to deliver requested message [%s].", body, name));
}
var msg = new SimpleMessage();
msg.addHeader(Headers.DATE, new Date().toString());
msg.addHeader(Headers.SENDER, name);
msg.setB... | 217 | 146 | 363 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/presentation-model/src/main/java/com/iluwatar/presentationmodel/DisplayedAlbums.java | DisplayedAlbums | addAlbums | class DisplayedAlbums {
/**
* albums a list of albums.
*/
private final List<Album> albums;
/**
* a constructor method.
*/
public DisplayedAlbums() {
this.albums = new ArrayList<>();
}
/**
* a method used to add a new album to album list.
*
* @param title the title of the al... |
if (isClassical) {
this.albums.add(new Album(title, artist, true, composer));
} else {
this.albums.add(new Album(title, artist, false, ""));
}
| 217 | 65 | 282 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/presentation-model/src/main/java/com/iluwatar/presentationmodel/PresentationModel.java | PresentationModel | getAlbumList | class PresentationModel {
/**
* the data of all albums that will be shown.
*/
private final DisplayedAlbums data;
/**
* the no of selected album.
*/
private int selectedAlbumNumber;
/**
* the selected album.
*/
private Album selectedAlbum;
/**
* Generates a set of data for testing.
... |
var result = new String[data.getAlbums().size()];
for (var i = 0; i < result.length; i++) {
result[i] = data.getAlbums().get(i).getTitle();
}
return result;
| 1,248 | 69 | 1,317 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/presentation-model/src/main/java/com/iluwatar/presentationmodel/View.java | View | createView | class View {
/**
* the model that controls this view.
*/
private final PresentationModel model;
/**
* the filed to show and modify title.
*/
private TextField txtTitle;
/**
* the filed to show and modify the name of artist.
*/
private TextField txtArtist;
/**
* the checkbox for is c... |
var frame = new JFrame("Album");
var b1 = Box.createHorizontalBox();
frame.add(b1);
albumList = new JList<>(model.getAlbumList());
albumList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
model.setSelectedAlbumNumber(albumList.get... | 628 | 577 | 1,205 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java | Application | main | class Application {
/**
* main entry.
*/
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
} |
var queueManager = new QueueManager(10);
// push some message to queue
// Low Priority message
for (var i = 0; i < 10; i++) {
queueManager.publishMessage(new Message("Low Message Priority", 0));
}
// High Priority message
for (var i = 0; i < 10; i++) {
queueManager.publishMes... | 44 | 150 | 194 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java | Message | toString | class Message implements Comparable<Message> {
private final String message;
private final int priority; // define message priority in queue
public Message(String message, int priority) {
this.message = message;
this.priority = priority;
}
@Override
public int compareTo(Message o) {
return pr... |
return "Message{"
+ "message='" + message + '\''
+ ", priority=" + priority
+ '}';
| 121 | 36 | 157 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java | PriorityMessageQueue | maxHeapifyUp | class PriorityMessageQueue<T extends Comparable> {
private int size = 0;
private int capacity;
private T[] queue;
public PriorityMessageQueue(T[] queue) {
this.queue = queue;
this.capacity = queue.length;
}
/**
* Remove top message from queue.
*/
public T remove() {
if (isEmpty()) ... |
var index = size - 1;
while (hasParent(index) && parent(index).compareTo(queue[index]) < 0) {
swap(parentIndex(index), index);
index = parentIndex(index);
}
| 873 | 61 | 934 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java | Worker | run | class Worker {
private final QueueManager queueManager;
public Worker(QueueManager queueManager) {
this.queueManager = queueManager;
}
/**
* Keep checking queue for message.
*/
@SuppressWarnings("squid:S2189")
public void run() throws Exception {<FILL_FUNCTION_BODY>}
/**
* Process message... |
while (true) {
var message = queueManager.receiveMessage();
if (message == null) {
LOGGER.info("No Message ... waiting");
Thread.sleep(200);
} else {
processMessage(message);
}
}
| 138 | 71 | 209 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
// stew is mutable
var stew = new Stew(1, 2, 3, 4);
stew.mix();
stew.taste();
stew.mix();
// immutable stew protected with Private Class Data pattern
var immutableStew = new ImmutableStew(2, 4, 3, 6);
immutableStew.mix();
| 56 | 102 | 158 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java | ImmutableStew | mix | class ImmutableStew {
private final StewData data;
public ImmutableStew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
data = new StewData(numPotatoes, numCarrots, numMeat, numPeppers);
}
/**
* Mix the stew.
*/
public void mix() {<FILL_FUNCTION_BODY>}
} |
LOGGER
.info("Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers",
data.numPotatoes(), data.numCarrots(), data.numMeat(), data.numPeppers());
| 117 | 66 | 183 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java | Stew | mix | class Stew {
private int numPotatoes;
private int numCarrots;
private int numMeat;
private int numPeppers;
/**
* Constructor.
*/
public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
this.numPotatoes = numPotatoes;
this.numCarrots = numCarrots;
this.num... |
LOGGER.info("Mixing the stew we find: {} potatoes, {} carrots, {} meat and {} peppers",
numPotatoes, numCarrots, numMeat, numPeppers);
| 346 | 57 | 403 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
var queue = new ItemQueue();
var executorService = Executors.newFixedThreadPool(5);
for (var i = 0; i < 2; i++) {
final var producer = new Producer("Producer_" + i, queue);
executorService.submit(() -> {
while (true) {
producer.produce();
}
});
}
for ... | 56 | 244 | 300 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java | Consumer | consume | class Consumer {
private final ItemQueue queue;
private final String name;
public Consumer(String name, ItemQueue queue) {
this.name = name;
this.queue = queue;
}
/**
* Consume item from the queue.
*/
public void consume() throws InterruptedException {<FILL_FUNCTION_BODY>}
} |
var item = queue.take();
LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name,
item.id(), item.producer());
| 98 | 48 | 146 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/promise/src/main/java/com/iluwatar/promise/App.java | App | calculateLowestFrequencyChar | class App {
private static final String DEFAULT_URL =
"https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/promise/README.md";
private final ExecutorService executor;
private final CountDownLatch stopLatch;
private App() {
executor = Executors.newFixedThreadPool(2);
stopLatch ... |
lowestFrequencyChar().thenAccept(
charFrequency -> {
LOGGER.info("Char with lowest frequency is: {}", charFrequency);
taskCompleted();
}
);
| 804 | 52 | 856 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/promise/src/main/java/com/iluwatar/promise/Promise.java | TransformAction | run | class TransformAction<V> implements Runnable {
private final Promise<T> src;
private final Promise<V> dest;
private final Function<? super T, V> func;
private TransformAction(Promise<T> src, Promise<V> dest, Function<? super T, V> func) {
this.src = src;
this.dest = dest;
this.func =... |
try {
dest.fulfill(func.apply(src.get()));
} catch (Throwable throwable) {
dest.fulfillExceptionally((Exception) throwable.getCause());
}
| 133 | 54 | 187 | <methods>public boolean cancel(boolean) ,public T get() throws java.lang.InterruptedException, java.util.concurrent.ExecutionException,public T get(long, java.util.concurrent.TimeUnit) throws java.util.concurrent.ExecutionException,public boolean isCancelled() ,public boolean isDone() <variables>private static final in... |
iluwatar_java-design-patterns | java-design-patterns/promise/src/main/java/com/iluwatar/promise/PromiseSupport.java | PromiseSupport | get | class PromiseSupport<T> implements Future<T> {
private static final Logger LOGGER = LoggerFactory.getLogger(PromiseSupport.class);
private static final int RUNNING = 1;
private static final int FAILED = 2;
private static final int COMPLETED = 3;
private final Object lock;
private volatile int state = RU... |
synchronized (lock) {
while (state == RUNNING) {
try {
lock.wait(unit.toMillis(timeout));
} catch (InterruptedException e) {
LOGGER.warn("Interrupted!", e);
Thread.currentThread().interrupt();
}
}
}
if (state == COMPLETED) {
return va... | 426 | 115 | 541 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/promise/src/main/java/com/iluwatar/promise/Utility.java | Utility | downloadFile | class Utility {
/**
* Calculates character frequency of the file provided.
*
* @param fileLocation location of the file.
* @return a map of character to its frequency, an empty map if file does not exist.
*/
public static Map<Character, Long> characterFrequency(String fileLocation) {
try (var bu... |
LOGGER.info("Downloading contents from url: {}", urlString);
var url = new URL(urlString);
var file = File.createTempFile("promise_pattern", null);
try (var bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
var writer = new FileWriter(file)) {
String line;
... | 500 | 161 | 661 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/property/src/main/java/com/iluwatar/property/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
/* set up */
var charProto = new Character();
charProto.set(Stats.STRENGTH, 10);
charProto.set(Stats.AGILITY, 10);
charProto.set(Stats.ARMOR, 10);
charProto.set(Stats.ATTACK_POWER, 10);
var mageProto = new Character(Type.MAGE, charProto);
mageProto.set(Stats.INTELLECT, 15);
magePro... | 56 | 430 | 486 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/property/src/main/java/com/iluwatar/property/Character.java | Character | toString | class Character implements Prototype {
/**
* Enumeration of Character types.
*/
public enum Type {
WARRIOR, MAGE, ROGUE
}
private final Prototype prototype;
private final Map<Stats, Integer> properties = new HashMap<>();
private String name;
private Type type;
/**
* Constructor.
*/
... |
var builder = new StringBuilder();
if (name != null) {
builder.append("Player: ").append(name).append('\n');
}
if (type != null) {
builder.append("Character type: ").append(type.name()).append('\n');
}
builder.append("Stats:\n");
for (var stat : Stats.values()) {
var val... | 521 | 169 | 690 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/prototype/src/main/java/com/iluwatar/prototype/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 = new HeroFactoryImpl(
new ElfMage("cooking"),
new ElfWarlord("cleaning"),
new ElfBeast("protecting")
);
var mage = factory.createMage();
var warlord = factory.createWarlord();
var beast = factory.createBeast();
LOGGER.info(mage.toString());
LOGGER.info(w... | 56 | 238 | 294 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/proxy/src/main/java/com/iluwatar/proxy/App.java | App | main | class App {
/**
* Program entry point.
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
var proxy = new WizardTowerProxy(new IvoryTower());
proxy.enter(new Wizard("Red wizard"));
proxy.enter(new Wizard("White wizard"));
proxy.enter(new Wizard("Black wizard"));
proxy.enter(new Wizard("Green wizard"));
proxy.enter(new Wizard("Brown wizard"));
| 44 | 95 | 139 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java | WizardTowerProxy | enter | class WizardTowerProxy implements WizardTower {
private static final int NUM_WIZARDS_ALLOWED = 3;
private int numWizards;
private final WizardTower tower;
public WizardTowerProxy(WizardTower tower) {
this.tower = tower;
}
@Override
public void enter(Wizard wizard) {<FILL_FUNCTION_BODY>}
} |
if (numWizards < NUM_WIZARDS_ALLOWED) {
tower.enter(wizard);
numWizards++;
} else {
LOGGER.info("{} is not allowed to enter!", wizard);
}
| 115 | 68 | 183 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java | App | main | class App {
//Executor shut down time limit.
private static final int SHUTDOWN_TIME = 15;
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
// An Executor that provides methods to manage termination and methods that can
// produce a Future for tracking progress of one or more asynchronous tasks.
ExecutorService executor = null;
try {
// Create a MessageQueue object.
var msgQueue = new MessageQueue();
LOGGER.info("Subm... | 82 | 473 | 555 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java | MessageQueue | submitMsg | class MessageQueue {
private final BlockingQueue<Message> blkQueue;
// Default constructor when called creates Blocking Queue object.
public MessageQueue() {
this.blkQueue = new ArrayBlockingQueue<>(1024);
}
/**
* All the TaskGenerator threads will call this method to insert the Messages in to the ... |
try {
if (null != msg) {
blkQueue.add(msg);
}
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
| 231 | 53 | 284 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java | ServiceExecutor | run | class ServiceExecutor implements Runnable {
private final MessageQueue msgQueue;
public ServiceExecutor(MessageQueue msgQueue) {
this.msgQueue = msgQueue;
}
/**
* The ServiceExecutor thread will retrieve each message and process it.
*/
public void run() {<FILL_FUNCTION_BODY>}
} |
try {
while (!Thread.currentThread().isInterrupted()) {
var msg = msgQueue.retrieveMsg();
if (null != msg) {
LOGGER.info(msg.toString() + " is served.");
} else {
LOGGER.info("Service Executor: Waiting for Messages to serve .. ");
}
Thread.sleep(1... | 88 | 126 | 214 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java | TaskGenerator | run | class TaskGenerator implements Task, Runnable {
// MessageQueue reference using which we will submit our messages.
private final MessageQueue msgQueue;
// Total message count that a TaskGenerator will submit.
private final int msgCount;
// Parameterized constructor.
public TaskGenerator(MessageQueue msgQ... |
var count = this.msgCount;
try {
while (count > 0) {
var statusMsg = "Message-" + count + " submitted by " + Thread.currentThread().getName();
this.submit(new Message(statusMsg));
LOGGER.info(statusMsg);
// reduce the message count.
count--;
// Make the... | 239 | 140 | 379 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/reactor/src/main/java/com/iluwatar/reactor/app/App.java | App | start | class App {
private NioReactor reactor;
private final List<AbstractNioChannel> channels = new ArrayList<>();
private final Dispatcher dispatcher;
/**
* Creates an instance of App which will use provided dispatcher for dispatching events on
* reactor.
*
* @param dispatcher the dispatcher that will ... |
/*
* The application can customize its event dispatching mechanism.
*/
reactor = new NioReactor(dispatcher);
/*
* This represents application specific business logic that dispatcher will call on appropriate
* events. These events are read events in our example.
*/
var loggingH... | 452 | 198 | 650 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java | UdpLoggingClient | run | class UdpLoggingClient implements Runnable {
private final String clientName;
private final InetSocketAddress remoteAddress;
/**
* Creates a new UDP logging client.
*
* @param clientName the name of the client to be sent in logging requests.
* @param port the port on which client ... |
try (var socket = new DatagramSocket()) {
for (var i = 0; i < 4; i++) {
var message = clientName + " - Log request: " + i;
var bytes = message.getBytes();
var request = new DatagramPacket(bytes, bytes.length, remoteAddress);
socket.send(request);
var d... | 185 | 229 | 414 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java | LoggingHandler | handleChannelRead | class LoggingHandler implements ChannelHandler {
private static final byte[] ACK = "Data logged successfully".getBytes();
/**
* Decodes the received data and logs it on standard console.
*/
@Override
public void handleChannelRead(AbstractNioChannel channel, Object readObject, SelectionKey key) {<FILL_FU... |
/*
* As this handler is attached with both TCP and UDP channels we need to check whether the data
* received is a ByteBuffer (from TCP channel) or a DatagramPacket (from UDP channel).
*/
if (readObject instanceof ByteBuffer) {
doLogging((ByteBuffer) readObject);
sendReply(channel, ke... | 313 | 164 | 477 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java | AbstractNioChannel | flush | class AbstractNioChannel {
private final SelectableChannel channel;
private final ChannelHandler handler;
private final Map<SelectableChannel, Queue<Object>> channelToPendingWrites;
private NioReactor reactor;
/**
* Creates a new channel.
*
* @param handler which will handle events occurring on thi... |
var pendingWrites = channelToPendingWrites.get(key.channel());
Object pendingWrite;
while ((pendingWrite = pendingWrites.poll()) != null) {
// ask the concrete channel to make sense of data and write it to java channel
doWrite(pendingWrite, key);
}
// We don't have anything more to writ... | 1,021 | 118 | 1,139 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java | NioDatagramChannel | read | class NioDatagramChannel extends AbstractNioChannel {
private final int port;
/**
* Creates a {@link DatagramChannel} which will bind at provided port and use <code>handler</code>
* to handle incoming events on this channel.
*
* <p>Note the constructor does not bind the socket, {@link #bind()} method ... |
var buffer = ByteBuffer.allocate(1024);
var sender = ((DatagramChannel) key.channel()).receive(buffer);
/*
* It is required to create a DatagramPacket because we need to preserve which socket address
* acts as destination for sending reply packets.
*/
buffer.flip();
var packet = new... | 1,105 | 114 | 1,219 | <methods>public void <init>(com.iluwatar.reactor.framework.ChannelHandler, java.nio.channels.SelectableChannel) ,public abstract void bind() throws java.io.IOException,public com.iluwatar.reactor.framework.ChannelHandler getHandler() ,public abstract int getInterestedOps() ,public java.nio.channels.SelectableChannel ge... |
iluwatar_java-design-patterns | java-design-patterns/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java | NioReactor | start | class NioReactor {
private final Selector selector;
private final Dispatcher dispatcher;
/**
* All the work of altering the SelectionKey operations and Selector operations are performed in
* the context of main event loop of reactor. So when any channel needs to change its readability
* or writability, ... |
reactorMain.execute(() -> {
try {
LOGGER.info("Reactor started, waiting for events...");
eventLoop();
} catch (IOException e) {
LOGGER.error("exception in event loop", e);
}
});
| 1,704 | 68 | 1,772 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/reactor/src/main/java/com/iluwatar/reactor/framework/SameThreadDispatcher.java | SameThreadDispatcher | onChannelReadEvent | class SameThreadDispatcher implements Dispatcher {
/**
* Dispatches the read event in the context of caller thread. <br> Note this is a blocking call.
* It returns only after the associated handler has handled the read event.
*/
@Override
public void onChannelReadEvent(AbstractNioChannel channel, Object... |
/*
* Calls the associated handler to notify the read event where application specific code
* resides.
*/
channel.getHandler().handleChannelRead(channel, readObject, key);
| 138 | 50 | 188 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
var executeService = Executors.newFixedThreadPool(10);
var lock = new ReaderWriterLock();
// Start writers
for (var i = 0; i < 5; i++) {
var writingTime = ThreadLocalRandom.current().nextLong(5000);
executeService.submit(new Writer("Writer " + i, lock.writeLock(), writingTime));
}
... | 57 | 434 | 491 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java | Reader | run | class Reader implements Runnable {
private final Lock readLock;
private final String name;
private final long readingTime;
/**
* Create new Reader.
*
* @param name - Name of the thread owning the reader
* @param readLock - Lock for this reader
* @param readingTime - amount of time (... |
readLock.lock();
try {
read();
} catch (InterruptedException e) {
LOGGER.info("InterruptedException when reading", e);
Thread.currentThread().interrupt();
} finally {
readLock.unlock();
}
| 331 | 69 | 400 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java | ReadLock | unlock | class ReadLock implements Lock {
@Override
public void lock() {
synchronized (readerMutex) {
currentReaderCount++;
if (currentReaderCount == 1) {
acquireForReaders();
}
}
}
/**
* Acquire the globalMutex lock on behalf of current and future concurrent ... |
synchronized (readerMutex) {
currentReaderCount--;
// Release the lock only when it is the last reader, it is ensure that the lock is released
// when all reader is completely.
if (currentReaderCount == 0) {
synchronized (globalMutex) {
// Notify the waiter, ... | 412 | 113 | 525 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java | Writer | run | class Writer implements Runnable {
private final Lock writeLock;
private final String name;
private final long writingTime;
/**
* Create new Writer who writes for 250ms.
*
* @param name - Name of the thread owning the writer
* @param writeLock - Lock for this writer
*/
public Writer(St... |
writeLock.lock();
try {
write();
} catch (InterruptedException e) {
LOGGER.info("InterruptedException when writing", e);
Thread.currentThread().interrupt();
} finally {
writeLock.unlock();
}
| 337 | 69 | 406 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/registry/src/main/java/com/iluwatar/registry/App.java | App | main | class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
CustomerRegistry customerRegistry = CustomerRegistry.getInstance();
var john = new Customer("1", "John");
customerRegistry.addCustomer(john);
var julia = new Customer("2", "Julia");
customerRegistry.addCustomer(julia);
LOGGER.info("John {}", customerRegistry.getCustomer("1"));
LOGGER.info... | 79 | 106 | 185 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/repository/src/main/java/com/iluwatar/repository/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
var context = new ClassPathXmlApplicationContext("applicationContext.xml");
var repository = context.getBean(PersonRepository.class);
var peter = new Person("Peter", "Sagan", 17);
var nasta = new Person("Nasta", "Kuzminova", 25);
var john = new Person("John", "lawrence", 35);
var terry = new ... | 56 | 480 | 536 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/repository/src/main/java/com/iluwatar/repository/AppConfig.java | AppConfig | main | class AppConfig {
/**
* Creation of H2 db.
*
* @return A new Instance of DataSource
*/
@Bean(destroyMethod = "close")
public DataSource dataSource() {
var basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName("org.h2.Driver");
basicDataSource.setUrl("jdbc:h2:mem:data... |
var context = new AnnotationConfigApplicationContext(AppConfig.class);
var repository = context.getBean(PersonRepository.class);
var peter = new Person("Peter", "Sagan", 17);
var nasta = new Person("Nasta", "Kuzminova", 25);
var john = new Person("John", "lawrence", 35);
var terry = new Person... | 481 | 471 | 952 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java | App | main | class App {
/**
* Program entry point.
*/
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
} |
try (var ignored = new SlidingDoor()) {
LOGGER.info("Walking in.");
}
try (var ignored = new TreasureChest()) {
LOGGER.info("Looting contents.");
}
| 46 | 62 | 108 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/retry/src/main/java/com/iluwatar/retry/App.java | App | errorWithRetry | class App {
private static final Logger LOG = LoggerFactory.getLogger(App.class);
public static final String NOT_FOUND = "not found";
private static BusinessOperation<String> op;
/**
* Entry point.
*
* @param args not used
* @throws Exception not expected
*/
public static void main(String[] ar... |
final var retry = new Retry<>(
new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)),
3, //3 attempts
100, //100 ms delay between attempts
e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass())
);
op = retry;
final var customerId = op.perform();... | 474 | 161 | 635 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/retry/src/main/java/com/iluwatar/retry/Retry.java | Retry | perform | class Retry<T> implements BusinessOperation<T> {
private final BusinessOperation<T> op;
private final int maxAttempts;
private final long delay;
private final AtomicInteger attempts;
private final Predicate<Exception> test;
private final List<Exception> errors;
/**
* Ctor.
*
* @param op ... |
do {
try {
return this.op.perform();
} catch (BusinessException e) {
this.errors.add(e);
if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) {
throw e;
}
try {
Thread.sleep(this.delay);
} catch (Interrupted... | 448 | 126 | 574 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java | RetryExponentialBackoff | perform | class RetryExponentialBackoff<T> implements BusinessOperation<T> {
private static final Random RANDOM = new Random();
private final BusinessOperation<T> op;
private final int maxAttempts;
private final long maxDelay;
private final AtomicInteger attempts;
private final Predicate<Exception> test;
private fi... |
do {
try {
return this.op.perform();
} catch (BusinessException e) {
this.errors.add(e);
if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) {
throw e;
}
try {
var testDelay = (long) Math.pow(2, this.attempts()) * ... | 457 | 181 | 638 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java | ApplicationRoleObject | main | class ApplicationRoleObject {
/**
* Main entry point.
*
* @param args program arguments
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
var customer = Customer.newCustomer(Borrower, Investor);
LOGGER.info(" the new customer created : {}", customer);
var hasBorrowerRole = customer.hasRole(Borrower);
LOGGER.info(" customer has a borrowed role - {}", hasBorrowerRole);
var hasInvestorRole = customer.hasRole(Investor);
LOGGER.info... | 57 | 293 | 350 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java | BorrowerRole | borrow | class BorrowerRole extends CustomerRole {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String borrow() {<FILL_FUNCTION_BODY>}
} |
return String.format("Borrower %s wants to get some money.", name);
| 80 | 23 | 103 | <methods>public non-sealed void <init>() <variables> |
iluwatar_java-design-patterns | java-design-patterns/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java | CustomerCore | toString | class CustomerCore extends Customer {
private final Map<Role, CustomerRole> roles;
public CustomerCore() {
roles = new HashMap<>();
}
@Override
public boolean addRole(Role role) {
return role
.instance()
.map(inst -> {
roles.put(role, inst);
return true;
... |
var roles = Arrays.toString(this.roles.keySet().toArray());
return "Customer{roles=" + roles + "}";
| 268 | 40 | 308 | <methods>public non-sealed void <init>() ,public abstract boolean addRole(com.iluwatar.roleobject.Role) ,public abstract Optional<T> getRole(com.iluwatar.roleobject.Role, Class<T>) ,public abstract boolean hasRole(com.iluwatar.roleobject.Role) ,public static com.iluwatar.roleobject.Customer newCustomer() ,public static... |
iluwatar_java-design-patterns | java-design-patterns/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java | InvestorRole | invest | class InvestorRole extends CustomerRole {
private String name;
private long amountToInvest;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getAmountToInvest() {
return amountToInvest;
}
public void setAmountToInvest(long am... |
return String.format("Investor %s has invested %d dollars", name, amountToInvest);
| 146 | 28 | 174 | <methods>public non-sealed void <init>() <variables> |
iluwatar_java-design-patterns | java-design-patterns/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java | Saga | getResult | class Saga {
private final List<Chapter> chapters;
private int pos;
private boolean forward;
private boolean finished;
public static Saga create() {
return new Saga();
}
/**
* get resuzlt of saga.
*
* @return result of saga @see {@link SagaResult}
*/
public SagaResult getResult() {<F... |
if (finished) {
return forward
? SagaResult.FINISHED
: SagaResult.ROLLBACKED;
}
return SagaResult.PROGRESS;
| 1,053 | 52 | 1,105 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/saga/src/main/java/com/iluwatar/saga/choreography/SagaApplication.java | SagaApplication | newSaga | class SagaApplication {
/**
* main method.
*/
public static void main(String[] args) {
var sd = serviceDiscovery();
var service = sd.findAny();
var goodOrderSaga = service.execute(newSaga("good_order"));
var badOrderSaga = service.execute(newSaga("bad_order"));
LOGGER.info("orders: goodOr... |
return Saga
.create()
.chapter("init an order").setInValue(value)
.chapter("booking a Fly")
.chapter("booking a Hotel")
.chapter("withdrawing Money");
| 251 | 62 | 313 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/saga/src/main/java/com/iluwatar/saga/choreography/Service.java | Service | isSagaFinished | class Service implements ChoreographyChapter {
protected static final Logger LOGGER = LoggerFactory.getLogger(Service.class);
private final ServiceDiscoveryService sd;
public Service(ServiceDiscoveryService service) {
this.sd = service;
}
@Override
public Saga execute(Saga saga) {
var nextSaga = ... |
if (!saga.isPresent()) {
saga.setFinished(true);
LOGGER.info(" the saga has been finished with {} status", saga.getResult());
return true;
}
return false;
| 652 | 61 | 713 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/saga/src/main/java/com/iluwatar/saga/choreography/WithdrawMoneyService.java | WithdrawMoneyService | process | class WithdrawMoneyService extends Service {
public WithdrawMoneyService(ServiceDiscoveryService service) {
super(service);
}
@Override
public String getName() {
return "withdrawing Money";
}
@Override
public Saga process(Saga saga) {<FILL_FUNCTION_BODY>}
} |
var inValue = saga.getCurrentValue();
if (inValue.equals("bad_order")) {
LOGGER.info("The chapter '{}' has been started. But the exception has been raised."
+ "The rollback is about to start",
getName(), inValue);
saga.setCurrentStatus(Saga.ChapterResult.ROLLBACK);
re... | 93 | 112 | 205 | <methods>public void <init>(com.iluwatar.saga.choreography.ServiceDiscoveryService) ,public com.iluwatar.saga.choreography.Saga execute(com.iluwatar.saga.choreography.Saga) ,public com.iluwatar.saga.choreography.Saga process(com.iluwatar.saga.choreography.Saga) ,public com.iluwatar.saga.choreography.Saga rollback(com.i... |
iluwatar_java-design-patterns | java-design-patterns/saga/src/main/java/com/iluwatar/saga/orchestration/HotelBookingService.java | HotelBookingService | rollback | class HotelBookingService extends Service<String> {
@Override
public String getName() {
return "booking a Hotel";
}
@Override
public ChapterResult<String> rollback(String value) {<FILL_FUNCTION_BODY>}
} |
if (value.equals("crashed_order")) {
LOGGER.info("The Rollback for a chapter '{}' has been started. "
+ "The data {} has been failed.The saga has been crashed.",
getName(), value);
return ChapterResult.failure(value);
}
LOGGER.info("The Rollback for a chapter '{}' has ... | 71 | 133 | 204 | <methods>public non-sealed void <init>() ,public abstract java.lang.String getName() ,public ChapterResult<java.lang.String> process(java.lang.String) ,public ChapterResult<java.lang.String> rollback(java.lang.String) <variables>protected static final Logger LOGGER |
iluwatar_java-design-patterns | java-design-patterns/saga/src/main/java/com/iluwatar/saga/orchestration/SagaApplication.java | SagaApplication | serviceDiscovery | class SagaApplication {
/**
* method to show common saga logic.
*/
public static void main(String[] args) {
var sagaOrchestrator = new SagaOrchestrator(newSaga(), serviceDiscovery());
Saga.Result goodOrder = sagaOrchestrator.execute("good_order");
Saga.Result badOrder = sagaOrchestrator.execute(... |
return new ServiceDiscoveryService()
.discover(new OrderService())
.discover(new FlyBookingService())
.discover(new HotelBookingService())
.discover(new WithdrawMoneyService());
| 267 | 59 | 326 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/saga/src/main/java/com/iluwatar/saga/orchestration/SagaOrchestrator.java | SagaOrchestrator | execute | class SagaOrchestrator {
private final Saga saga;
private final ServiceDiscoveryService sd;
private final CurrentState state;
/**
* Create a new service to orchetrate sagas.
*
* @param saga saga to process
* @param sd service discovery @see {@link ServiceDiscoveryService}
*/
public SagaOrch... |
state.cleanUp();
LOGGER.info(" The new saga is about to start");
var result = FINISHED;
K tempVal = value;
while (true) {
var next = state.current();
var ch = saga.get(next);
var srvOpt = sd.find(ch.name);
if (srvOpt.isEmpty()) {
state.directionToBack();
st... | 414 | 341 | 755 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/saga/src/main/java/com/iluwatar/saga/orchestration/Service.java | Service | process | class Service<K> implements OrchestrationChapter<K> {
protected static final Logger LOGGER = LoggerFactory.getLogger(Service.class);
@Override
public abstract String getName();
@Override
public ChapterResult<K> process(K value) {<FILL_FUNCTION_BODY>}
@Override
public ChapterResult<K> rollback(K value)... |
LOGGER.info("The chapter '{}' has been started. "
+ "The data {} has been stored or calculated successfully",
getName(), value);
return ChapterResult.success(value);
| 161 | 51 | 212 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/saga/src/main/java/com/iluwatar/saga/orchestration/WithdrawMoneyService.java | WithdrawMoneyService | process | class WithdrawMoneyService extends Service<String> {
@Override
public String getName() {
return "withdrawing Money";
}
@Override
public ChapterResult<String> process(String value) {<FILL_FUNCTION_BODY>}
} |
if (value.equals("bad_order") || value.equals("crashed_order")) {
LOGGER.info("The chapter '{}' has been started. But the exception has been raised."
+ "The rollback is about to start",
getName(), value);
return ChapterResult.failure(value);
}
return super.process(value)... | 70 | 91 | 161 | <methods>public non-sealed void <init>() ,public abstract java.lang.String getName() ,public ChapterResult<java.lang.String> process(java.lang.String) ,public ChapterResult<java.lang.String> rollback(java.lang.String) <variables>protected static final Logger LOGGER |
iluwatar_java-design-patterns | java-design-patterns/separated-interface/src/main/java/com/iluwatar/separatedinterface/App.java | App | main | class App {
public static final double PRODUCT_COST = 50.0;
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
//Create the invoice generator with product cost as 50 and foreign product tax
var internationalProductInvoice = new InvoiceGenerator(PRODUCT_COST,
new ForeignTaxCalculator());
LOGGER.info("Foreign Tax applied: {}", "" + internationalProductInvoice.getAmountWithTax());
//Create the invoice gen... | 75 | 149 | 224 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java | App | main | class App {
private static final String DB_URL = "jdbc:h2:mem:testdb";
private App() {
}
/**
* Program entry point.
* @param args command line args.
* @throws IOException if any
* @throws ClassNotFoundException if any
*/
public static void main(String[] args) throws IOException, ClassNotFoun... |
final var dataSource = createDataSource();
deleteSchema(dataSource);
createSchema(dataSource);
// Initializing Country Object China
final var China = new Country(
86,
"China",
"Asia",
"Chinese"
);
// Initializing Country Object UnitedArabEm... | 333 | 413 | 746 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountrySchemaSql.java | CountrySchemaSql | selectCountry | class CountrySchemaSql implements CountryDao {
public static final String CREATE_SCHEMA_SQL = "CREATE TABLE IF NOT EXISTS WORLD (ID INT PRIMARY KEY, COUNTRY BLOB)";
public static final String DELETE_SCHEMA_SQL = "DROP TABLE WORLD IF EXISTS";
private Country country;
private DataSource dataSource;
/**
* ... |
var sql = "SELECT ID, COUNTRY FROM WORLD WHERE ID = ?";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setInt(1, country.getCode());
try (ResultSet rs = preparedStatement.executeQuery()) {
if (rs.nex... | 563 | 233 | 796 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/servant/src/main/java/com/iluwatar/servant/App.java | App | scenario | class App {
private static final Servant jenkins = new Servant("Jenkins");
private static final Servant travis = new Servant("Travis");
/**
* Program entry point.
*/
public static void main(String[] args) {
scenario(jenkins, 1);
scenario(travis, 0);
}
/**
* Can add a List with enum Actio... |
var k = new King();
var q = new Queen();
var guests = List.of(k, q);
// feed
servant.feed(k);
servant.feed(q);
// serve drinks
servant.giveWine(k);
servant.giveWine(q);
// compliment
servant.giveCompliments(guests.get(compliment));
// outcome of the night
guests.f... | 144 | 195 | 339 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/servant/src/main/java/com/iluwatar/servant/King.java | King | changeMood | class King implements Royalty {
private boolean isDrunk;
private boolean isHungry = true;
private boolean isHappy;
private boolean complimentReceived;
@Override
public void getFed() {
isHungry = false;
}
@Override
public void getDrink() {
isDrunk = true;
}
public void receiveCompliment... |
if (!isHungry && isDrunk) {
isHappy = true;
}
if (complimentReceived) {
isHappy = false;
}
| 166 | 47 | 213 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/servant/src/main/java/com/iluwatar/servant/Queen.java | Queen | changeMood | class Queen implements Royalty {
private boolean isDrunk = true;
private boolean isHungry;
private boolean isHappy;
private boolean isFlirty = true;
private boolean complimentReceived;
@Override
public void getFed() {
isHungry = false;
}
@Override
public void getDrink() {
isDrunk = true;
... |
if (complimentReceived && isFlirty && isDrunk && !isHungry) {
isHappy = true;
}
| 204 | 37 | 241 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/server-session/src/main/java/com/iluwatar/sessionserver/App.java | App | sessionExpirationTask | class App {
// Map to store session data (simulated using a HashMap)
private static Map<String, Integer> sessions = new HashMap<>();
private static Map<String, Instant> sessionCreationTimes = new HashMap<>();
private static final long SESSION_EXPIRATION_TIME = 10000;
/**
* Main entry point.
* @param a... |
new Thread(() -> {
while (true) {
try {
LOGGER.info("Session expiration checker started...");
Thread.sleep(SESSION_EXPIRATION_TIME); // Sleep for expiration time
Instant currentTime = Instant.now();
synchronized (sessions) {
synchronized (sessionCre... | 300 | 267 | 567 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/server-session/src/main/java/com/iluwatar/sessionserver/LoginHandler.java | LoginHandler | handle | class LoginHandler implements HttpHandler {
private Map<String, Integer> sessions;
private Map<String, Instant> sessionCreationTimes;
public LoginHandler(Map<String, Integer> sessions, Map<String, Instant> sessionCreationTimes) {
this.sessions = sessions;
this.sessionCreationTimes = sessionCreationTimes... |
// Generate session ID
String sessionId = UUID.randomUUID().toString();
// Store session data (simulated)
int newUser = sessions.size() + 1;
sessions.put(sessionId, newUser);
sessionCreationTimes.put(sessionId, Instant.now());
LOGGER.info("User " + newUser + " created at time " + sessionCr... | 120 | 262 | 382 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/server-session/src/main/java/com/iluwatar/sessionserver/LogoutHandler.java | LogoutHandler | handle | class LogoutHandler implements HttpHandler {
private Map<String, Integer> sessions;
private Map<String, Instant> sessionCreationTimes;
public LogoutHandler(Map<String, Integer> sessions, Map<String, Instant> sessionCreationTimes) {
this.sessions = sessions;
this.sessionCreationTimes = sessionCreationTim... |
// Get session ID from cookie
String sessionId = exchange.getRequestHeaders().getFirst("Cookie").replace("sessionID=", "");
String currentSessionId = sessions.get(sessionId) == null ? null : sessionId;
// Send response
String response = "";
if (currentSessionId == null) {
response += "S... | 122 | 308 | 430 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java | App | initData | class App {
public static final String BOOK_OF_IDORES = "Book of Idores";
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
// populate the in-memory database
initData();
// query the data using the service
queryData();
}
/**... |
// spells
var spell1 = new Spell("Ice dart");
var spell2 = new Spell("Invisibility");
var spell3 = new Spell("Stun bolt");
var spell4 = new Spell("Confusion");
var spell5 = new Spell("Darkness");
var spell6 = new Spell("Fireball");
var spell7 = new Spell("Enchant weapon");
var spell... | 507 | 1,489 | 1,996 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java | DaoBaseImpl | merge | class DaoBaseImpl<E extends BaseEntity> implements Dao<E> {
@SuppressWarnings("unchecked")
protected Class<E> persistentClass = (Class<E>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
/*
* Making this getSessionFactory() instead of getSession() so that it is the... |
Transaction tx = null;
E result = null;
try (var session = getSessionFactory().openSession()) {
tx = session.beginTransaction();
result = (E) session.merge(entity);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
}
ret... | 773 | 103 | 876 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java | HibernateUtil | getSessionFactory | class HibernateUtil {
/**
* The cached session factory.
*/
private static volatile SessionFactory sessionFactory;
private HibernateUtil() {
}
/**
* Create the current session factory instance, create a new one when there is none yet.
*
* @return The session factory
*/
public static sync... |
if (sessionFactory == null) {
try {
sessionFactory = new Configuration()
.addAnnotatedClass(Wizard.class)
.addAnnotatedClass(Spellbook.class)
.addAnnotatedClass(Spell.class)
.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
... | 183 | 244 | 427 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java | MagicServiceImpl | findWizardsWithSpell | class MagicServiceImpl implements MagicService {
private final WizardDao wizardDao;
private final SpellbookDao spellbookDao;
private final SpellDao spellDao;
/**
* Constructor.
*/
public MagicServiceImpl(WizardDao wizardDao, SpellbookDao spellbookDao, SpellDao spellDao) {
this.wizardDao = wizardDa... |
var spell = spellDao.findByName(name);
var spellbook = spell.getSpellbook();
return new ArrayList<>(spellbook.getWizards());
| 344 | 47 | 391 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java | SpellDaoImpl | findByName | class SpellDaoImpl extends DaoBaseImpl<Spell> implements SpellDao {
@Override
public Spell findByName(String name) {<FILL_FUNCTION_BODY>}
} |
Transaction tx = null;
Spell result;
try (var session = getSessionFactory().openSession()) {
tx = session.beginTransaction();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Spell> builderQuery = criteriaBuilder.createQuery(Spell.class);
Root<Spell> roo... | 54 | 197 | 251 | <methods>public non-sealed void <init>() ,public void delete(com.iluwatar.servicelayer.spell.Spell) ,public com.iluwatar.servicelayer.spell.Spell find(java.lang.Long) ,public List<com.iluwatar.servicelayer.spell.Spell> findAll() ,public com.iluwatar.servicelayer.spell.Spell merge(com.iluwatar.servicelayer.spell.Spell) ... |
iluwatar_java-design-patterns | java-design-patterns/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java | SpellbookDaoImpl | findByName | class SpellbookDaoImpl extends DaoBaseImpl<Spellbook> implements SpellbookDao {
@Override
public Spellbook findByName(String name) {<FILL_FUNCTION_BODY>}
} |
Transaction tx = null;
Spellbook result;
try (var session = getSessionFactory().openSession()) {
tx = session.beginTransaction();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Spellbook> builderQuery = criteriaBuilder.createQuery(Spellbook.class);
Roo... | 59 | 203 | 262 | <methods>public non-sealed void <init>() ,public void delete(com.iluwatar.servicelayer.spellbook.Spellbook) ,public com.iluwatar.servicelayer.spellbook.Spellbook find(java.lang.Long) ,public List<com.iluwatar.servicelayer.spellbook.Spellbook> findAll() ,public com.iluwatar.servicelayer.spellbook.Spellbook merge(com.ilu... |
iluwatar_java-design-patterns | java-design-patterns/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java | WizardDaoImpl | findByName | class WizardDaoImpl extends DaoBaseImpl<Wizard> implements WizardDao {
@Override
public Wizard findByName(String name) {<FILL_FUNCTION_BODY>}
} |
Transaction tx = null;
Wizard result;
try (var session = getSessionFactory().openSession()) {
tx = session.beginTransaction();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Wizard> builderQuery = criteriaBuilder.createQuery(Wizard.class);
Root<Wizard>... | 54 | 197 | 251 | <methods>public non-sealed void <init>() ,public void delete(com.iluwatar.servicelayer.wizard.Wizard) ,public com.iluwatar.servicelayer.wizard.Wizard find(java.lang.Long) ,public List<com.iluwatar.servicelayer.wizard.Wizard> findAll() ,public com.iluwatar.servicelayer.wizard.Wizard merge(com.iluwatar.servicelayer.wizar... |
iluwatar_java-design-patterns | java-design-patterns/service-locator/src/main/java/com/iluwatar/servicelocator/App.java | App | main | class App {
public static final String JNDI_SERVICE_A = "jndi/serviceA";
public static final String JNDI_SERVICE_B = "jndi/serviceB";
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
var service = ServiceLocator.getService(JNDI_SERVICE_A);
service.execute();
service = ServiceLocator.getService(JNDI_SERVICE_B);
service.execute();
service = ServiceLocator.getService(JNDI_SERVICE_A);
service.execute();
service = ServiceLocator.getService(JNDI_SERVICE_A);
service.execut... | 103 | 108 | 211 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/service-locator/src/main/java/com/iluwatar/servicelocator/InitContext.java | InitContext | lookup | class InitContext {
/**
* Perform the lookup based on the service name. The returned object will need to be casted into a
* {@link Service}
*
* @param serviceName a string
* @return an {@link Object}
*/
public Object lookup(String serviceName) {<FILL_FUNCTION_BODY>}
} |
if (serviceName.equals("jndi/serviceA")) {
LOGGER.info("Looking up service A and creating new service for A");
return new ServiceImpl("jndi/serviceA");
} else if (serviceName.equals("jndi/serviceB")) {
LOGGER.info("Looking up service B and creating new service for B");
return new Servic... | 90 | 116 | 206 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceCache.java | ServiceCache | getService | class ServiceCache {
private final Map<String, Service> serviceCache;
public ServiceCache() {
serviceCache = new HashMap<>();
}
/**
* Get the service from the cache. null if no service is found matching the name
*
* @param serviceName a string
* @return {@link Service}
*/
public Service ... |
if (serviceCache.containsKey(serviceName)) {
var cachedService = serviceCache.get(serviceName);
var name = cachedService.getName();
var id = cachedService.getId();
LOGGER.info("(cache call) Fetched service {}({}) from cache... !", name, id);
return cachedService;
}
return null... | 177 | 93 | 270 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceImpl.java | ServiceImpl | execute | class ServiceImpl implements Service {
private final String serviceName;
private final int id;
/**
* Constructor.
*/
public ServiceImpl(String serviceName) {
// set the service name
this.serviceName = serviceName;
// Generate a random id to this service object
this.id = (int) Math.floor... |
LOGGER.info("Service {} is now executing with id {}", getName(), getId());
| 176 | 25 | 201 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java | ServiceLocator | getService | class ServiceLocator {
private static final ServiceCache serviceCache = new ServiceCache();
private ServiceLocator() {
}
/**
* Fetch the service with the name param from the cache first, if no service is found, lookup the
* service from the {@link InitContext} and then add the newly created service int... |
var serviceObj = serviceCache.getService(serviceJndiName);
if (serviceObj != null) {
return serviceObj;
} else {
/*
* If we are unable to retrieve anything from cache, then lookup the service and add it in the
* cache map
*/
var ctx = new InitContext();
serviceO... | 147 | 147 | 294 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/service-to-worker/src/main/java/com/iluwatar/servicetoworker/App.java | App | main | class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
// create model, view and controller
var giant1 = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
var giant2 = new GiantModel("giant2", Health.DEAD, Fatigue.SLEEPING, Nourishment.STARVING);
var action1 = new Action(giant1);
var action2 = new Action(giant2);
var v... | 56 | 322 | 378 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantModel.java | GiantModel | toString | class GiantModel {
private final com.iluwatar.model.view.controller.GiantModel model;
@Getter
private final String name;
/**
* Instantiates a new Giant model.
*
* @param name the name
* @param health the health
* @param fatigue the fatigue
* @param nourishment the nourishment... |
return String
.format("Giant %s, The giant looks %s, %s and %s.", name,
model.getHealth(), model.getFatigue(), model.getNourishment());
| 474 | 52 | 526 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/sharding/src/main/java/com/iluwatar/sharding/App.java | App | main | class App {
/**
* Program main entry point.
*
* @param args program runtime arguments
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
var data1 = new Data(1, "data1", Data.DataType.TYPE_1);
var data2 = new Data(2, "data2", Data.DataType.TYPE_2);
var data3 = new Data(3, "data3", Data.DataType.TYPE_3);
var data4 = new Data(4, "data4", Data.DataType.TYPE_1);
var shard1 = new Shard(1);
var shard2 = new Shard(2);
var shard3 ... | 58 | 546 | 604 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/sharding/src/main/java/com/iluwatar/sharding/Data.java | Data | toString | class Data {
private int key;
private String value;
private DataType type;
/**
* Constructor of Data class.
* @param key data key
* @param value data vlue
* @param type data type
*/
public Data(final int key, final String value, final DataType type) {
this.key = key;
this.value = va... |
return "Data {" + "key="
+ key + ", value='" + value
+ '\'' + ", type=" + type + '}';
| 288 | 41 | 329 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/sharding/src/main/java/com/iluwatar/sharding/HashShardManager.java | HashShardManager | allocateShard | class HashShardManager extends ShardManager {
@Override
public int storeData(Data data) {
var shardId = allocateShard(data);
var shard = shardMap.get(shardId);
shard.storeData(data);
LOGGER.info(data.toString() + " is stored in Shard " + shardId);
return shardId;
}
@Override
protected in... |
var shardCount = shardMap.size();
var hash = data.getKey() % shardCount;
return hash == 0 ? hash + shardCount : hash;
| 134 | 46 | 180 | <methods>public void <init>() ,public boolean addNewShard(com.iluwatar.sharding.Shard) ,public com.iluwatar.sharding.Shard getShardById(int) ,public boolean removeShardById(int) ,public abstract int storeData(com.iluwatar.sharding.Data) <variables>protected Map<java.lang.Integer,com.iluwatar.sharding.Shard> shardMap |
iluwatar_java-design-patterns | java-design-patterns/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java | LookupShardManager | allocateShard | class LookupShardManager extends ShardManager {
private final Map<Integer, Integer> lookupMap = new HashMap<>();
@Override
public int storeData(Data data) {
var shardId = allocateShard(data);
lookupMap.put(data.getKey(), shardId);
var shard = shardMap.get(shardId);
shard.storeData(data);
LOG... |
var key = data.getKey();
if (lookupMap.containsKey(key)) {
return lookupMap.get(key);
} else {
var shardCount = shardMap.size();
return new SecureRandom().nextInt(shardCount - 1) + 1;
}
| 170 | 79 | 249 | <methods>public void <init>() ,public boolean addNewShard(com.iluwatar.sharding.Shard) ,public com.iluwatar.sharding.Shard getShardById(int) ,public boolean removeShardById(int) ,public abstract int storeData(com.iluwatar.sharding.Data) <variables>protected Map<java.lang.Integer,com.iluwatar.sharding.Shard> shardMap |
iluwatar_java-design-patterns | java-design-patterns/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java | RangeShardManager | storeData | class RangeShardManager extends ShardManager {
@Override
public int storeData(Data data) {<FILL_FUNCTION_BODY>}
@Override
protected int allocateShard(Data data) {
var type = data.getType();
return switch (type) {
case TYPE_1 -> 1;
case TYPE_2 -> 2;
case TYPE_3 -> 3;
default -> ... |
var shardId = allocateShard(data);
var shard = shardMap.get(shardId);
shard.storeData(data);
LOGGER.info(data.toString() + " is stored in Shard " + shardId);
return shardId;
| 122 | 74 | 196 | <methods>public void <init>() ,public boolean addNewShard(com.iluwatar.sharding.Shard) ,public com.iluwatar.sharding.Shard getShardById(int) ,public boolean removeShardById(int) ,public abstract int storeData(com.iluwatar.sharding.Data) <variables>protected Map<java.lang.Integer,com.iluwatar.sharding.Shard> shardMap |
iluwatar_java-design-patterns | java-design-patterns/sharding/src/main/java/com/iluwatar/sharding/ShardManager.java | ShardManager | removeShardById | class ShardManager {
protected Map<Integer, Shard> shardMap;
public ShardManager() {
shardMap = new HashMap<>();
}
/**
* Add a provided shard instance to shardMap.
*
* @param shard new shard instance.
* @return {@code true} if succeed to add the new instance.
* {@code false} if the... |
if (shardMap.containsKey(shardId)) {
shardMap.remove(shardId);
return true;
} else {
return false;
}
| 484 | 49 | 533 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/single-table-inheritance/src/main/java/com/iluwatar/SingleTableInheritance.java | SingleTableInheritance | run | class SingleTableInheritance implements CommandLineRunner {
//Autowiring the VehicleService class to execute the business logic methods
private final VehicleService vehicleService;
/**
* The entry point of the Spring Boot Application.
*
* @param args program runtime arguments
*/
public static void... |
Logger log = LoggerFactory.getLogger(SingleTableInheritance.class);
log.info("Saving Vehicles :- ");
// Saving Car to DB as a Vehicle
Vehicle vehicle1 = new Car("Tesla", "Model S", 4, 825);
Vehicle car1 = vehicleService.saveVehicle(vehicle1);
log.info("Vehicle 1 saved : {}", car1);
// S... | 176 | 437 | 613 | <no_super_class> |
iluwatar_java-design-patterns | java-design-patterns/single-table-inheritance/src/main/java/com/iluwatar/entity/Freighter.java | Freighter | toString | class Freighter extends TransportVehicle {
private double flightLength;
public Freighter(String manufacturer, String model, int loadCapacity, double flightLength) {
super(manufacturer, model, loadCapacity);
this.flightLength = flightLength;
}
// Overridden the toString method to specify the Vehicle o... |
return "Freighter{ "
+ super.toString()
+ " ,"
+ "flightLength="
+ flightLength
+ '}';
| 114 | 45 | 159 | <methods><variables>private int loadCapacity |
iluwatar_java-design-patterns | java-design-patterns/single-table-inheritance/src/main/java/com/iluwatar/entity/Truck.java | Truck | toString | class Truck extends TransportVehicle {
private int towingCapacity;
public Truck(String manufacturer, String model, int loadCapacity, int towingCapacity) {
super(manufacturer, model, loadCapacity);
this.towingCapacity = towingCapacity;
}
// Overridden the toString method to specify the Vehicle object
... |
return "Truck{ "
+ super.toString()
+ ", "
+ "towingCapacity="
+ towingCapacity
+ '}';
| 120 | 47 | 167 | <methods><variables>private int loadCapacity |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.