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 HTML, CSS, JS etc...
*
* <p>For illustrations purposes only, a very simple static html app is used here. This main
* method just fires up this simple web app in a default browser.
*
* @param args arguments
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
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);
} else {
// java Desktop not supported - above unlikely to work for Windows so try instead...
Runtime.getRuntime().exec("cmd.exe start " + applicationFile);
}
} catch (IOException ex) {
LOGGER.error("An error occurred.", ex);
}
| 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
* needed for having default values for one argument in each case. Hence multiple overloaded
* methods are needed as the number of argument increases.
*/
public String search(String type, String sortBy) {
return getQuerySummary(type, sortBy, SortOrder.ASC);
}
public String search(String type, SortOrder sortOrder) {
return getQuerySummary(type, "price", sortOrder);
}
/**
* The need for multiple method definitions can be avoided by the Parameter Object pattern.
* Below is the example where only one method is required and all the logic for having default
* values are abstracted into the Parameter Object at the time of object creation.
*/
public String search(ParameterObject parameterObject) {
return getQuerySummary(parameterObject.getType(), parameterObject.getSortBy(),
parameterObject.getSortOrder());
}
private String getQuerySummary(String type, String sortBy, SortOrder sortOrder) {<FILL_FUNCTION_BODY>}
}
|
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",
"Christopher Nolan", "English")
);
var videoResource = new VideoResource(new FieldJsonMapper(), videos);
LOGGER.info("Retrieving full response from server:-");
LOGGER.info("Get all video information:");
var videoDetails = videoResource.getDetails(1);
LOGGER.info(videoDetails);
LOGGER.info("----------------------------------------------------------");
LOGGER.info("Retrieving partial response from server:-");
LOGGER.info("Get video @id, @title, @director:");
var specificFieldsDetails = videoResource.getDetails(3, "id", "title", "director");
LOGGER.info(specificFieldsDetails);
LOGGER.info("Get video @id, @length:");
var videoLength = videoResource.getDetails(3, "id", "length");
LOGGER.info(videoLength);
| 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 = new StringBuilder().append("{");
var i = 0;
var fieldsLength = fields.length;
while (i < fieldsLength) {
json.append(getString(video, Video.class.getDeclaredField(fields[i])));
if (i != fieldsLength - 1) {
json.append(",");
}
i++;
}
json.append("}");
return json.toString();
}
private String getString(Video video, Field declaredField) throws IllegalAccessException {<FILL_FUNCTION_BODY>}
}
|
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) {<FILL_FUNCTION_BODY>}
}
|
/*
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 input.
- Stage handler 2 (pipe): Removing the digits, accepts a String input and returns the
processed String output. This shall also be used by the last handler we have.
- Stage handler 3 (pipe): Converting the String input to a char array handler. We would
be returning a different type in here since that is what's specified by the requirement.
This means that at any stages along the pipeline, the handler can return any type of data
as long as it fulfills the requirements for the next handler's input.
Suppose we wanted to add another handler after ConvertToCharArrayHandler. That handler
then is expected to receive an input of char[] array since that is the type being returned
by the previous handler, ConvertToCharArrayHandler.
*/
var filters = new Pipeline<>(new RemoveAlphabetsHandler())
.addHandler(new RemoveDigitsHandler())
.addHandler(new ConvertToCharArrayHandler());
filters.execute("GoYankees123!");
| 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 characters;
| 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.toString();
LOGGER.info(
String.format(
"Current handler: %s, input is %s of type %s, output is %s, of type %s",
RemoveAlphabetsHandler.class, input,
String.class, inputWithoutAlphabetsStr, String.class
)
);
return inputWithoutAlphabetsStr;
| 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.info(
String.format(
"Current handler: %s, input is %s of type %s, output is %s, of type %s",
RemoveDigitsHandler.class, input, String.class, inputWithoutDigitsStr, String.class
)
);
return inputWithoutDigitsStr;
| 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 information");
producer.send("bye!");
producer.stop();
}).start();
| 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("Message [{}] from [{}] received by [{}]", body, sender, name);
} catch (InterruptedException e) {
// allow thread to exit
LOGGER.error("Exception caught.", e);
return;
}
}
| 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.
*/
public void send(String body) {<FILL_FUNCTION_BODY>}
/**
* Stop system by sending poison pill.
*/
public void stop() {
isStopped = true;
try {
queue.put(Message.POISON_PILL);
} catch (InterruptedException e) {
// allow thread to exit
LOGGER.error("Exception caught.", e);
}
}
}
|
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.setBody(body);
try {
queue.put(msg);
} catch (InterruptedException e) {
// allow thread to exit
LOGGER.error("Exception caught.", e);
}
| 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 album.
* @param artist the artist name of the album.
* @param isClassical is the album classical, true or false.
* @param composer only when the album is classical,
* composer can have content.
*/
public void addAlbums(final String title,
final String artist, final boolean isClassical,
final String composer) {<FILL_FUNCTION_BODY>}
}
|
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.
*
* @return a instance of DsAlbum which store the data.
*/
public static DisplayedAlbums albumDataSet() {
var titleList = new String[]{"HQ", "The Rough Dancer and Cyclical Night",
"The Black Light", "Symphony No.5"};
var artistList = new String[]{"Roy Harper", "Astor Piazzola",
"The Black Light", "CBSO"};
var isClassicalList = new boolean[]{false, false, false, true};
var composerList = new String[]{null, null, null, "Sibelius"};
var result = new DisplayedAlbums();
for (var i = 1; i <= titleList.length; i++) {
result.addAlbums(titleList[i - 1], artistList[i - 1],
isClassicalList[i - 1], composerList[i - 1]);
}
return result;
}
/**
* constructor method.
*
* @param dataOfAlbums the data of all the albums
*/
public PresentationModel(final DisplayedAlbums dataOfAlbums) {
this.data = dataOfAlbums;
this.selectedAlbumNumber = 1;
this.selectedAlbum = this.data.getAlbums().get(0);
}
/**
* Changes the value of selectedAlbumNumber.
*
* @param albumNumber the number of album which is shown on the view.
*/
public void setSelectedAlbumNumber(final int albumNumber) {
LOGGER.info("Change select number from {} to {}",
this.selectedAlbumNumber, albumNumber);
this.selectedAlbumNumber = albumNumber;
this.selectedAlbum = data.getAlbums().get(this.selectedAlbumNumber - 1);
}
/**
* get the title of selected album.
*
* @return the tile of selected album.
*/
public String getTitle() {
return selectedAlbum.getTitle();
}
/**
* set the title of selected album.
*
* @param value the title which user want to user.
*/
public void setTitle(final String value) {
LOGGER.info("Change album title from {} to {}",
selectedAlbum.getTitle(), value);
selectedAlbum.setTitle(value);
}
/**
* get the artist of selected album.
*
* @return the artist of selected album.
*/
public String getArtist() {
return selectedAlbum.getArtist();
}
/**
* set the name of artist.
*
* @param value the name want artist to be.
*/
public void setArtist(final String value) {
LOGGER.info("Change album artist from {} to {}",
selectedAlbum.getArtist(), value);
selectedAlbum.setArtist(value);
}
/**
* Gets a boolean value which represents whether the album is classical.
*
* @return is the album classical.
*/
public boolean getIsClassical() {
return selectedAlbum.isClassical();
}
/**
* set the isClassical of album.
*
* @param value is the album classical.
*/
public void setIsClassical(final boolean value) {
LOGGER.info("Change album isClassical from {} to {}",
selectedAlbum.isClassical(), value);
selectedAlbum.setClassical(value);
}
/**
* get is classical of the selected album.
*
* @return is the album classical.
*/
public String getComposer() {
return selectedAlbum.isClassical() ? selectedAlbum.getComposer() : "";
}
/**
* Sets the name of composer when the album is classical.
*
* @param value the name of composer.
*/
public void setComposer(final String value) {
if (selectedAlbum.isClassical()) {
LOGGER.info("Change album composer from {} to {}",
selectedAlbum.getComposer(), value);
selectedAlbum.setComposer(value);
} else {
LOGGER.info("Composer can not be changed");
}
}
/**
* Gets a list of albums.
*
* @return the names of all the albums.
*/
public String[] getAlbumList() {<FILL_FUNCTION_BODY>}
}
|
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 classical.
*/
private JCheckBox chkClassical;
/**
* the filed to show and modify composer.
*/
private TextField txtComposer;
/**
* a list to show all the name of album.
*/
private JList<String> albumList;
/**
* a button to apply of all the change.
*/
private JButton apply;
/**
* roll back the change.
*/
private JButton cancel;
/**
* the value of the text field size.
*/
static final int WIDTH_TXT = 200;
static final int HEIGHT_TXT = 50;
/**
* the value of the GUI size and location.
*/
static final int LOCATION_X = 200;
static final int LOCATION_Y = 200;
static final int WIDTH = 500;
static final int HEIGHT = 300;
/**
* constructor method.
*/
public View() {
model = new PresentationModel(PresentationModel.albumDataSet());
}
/**
* save the data to PresentationModel.
*/
public void saveToMod() {
LOGGER.info("Save data to PresentationModel");
model.setArtist(txtArtist.getText());
model.setTitle(txtTitle.getText());
model.setIsClassical(chkClassical.isSelected());
model.setComposer(txtComposer.getText());
}
/**
* load the data from PresentationModel.
*/
public void loadFromMod() {
LOGGER.info("Load data from PresentationModel");
txtArtist.setText(model.getArtist());
txtTitle.setText(model.getTitle());
chkClassical.setSelected(model.getIsClassical());
txtComposer.setEditable(model.getIsClassical());
txtComposer.setText(model.getComposer());
}
/**
* initialize the GUI.
*/
public void createView() {<FILL_FUNCTION_BODY>}
}
|
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.getSelectedIndex() + 1);
loadFromMod();
}
});
b1.add(albumList);
var b2 = Box.createVerticalBox();
b1.add(b2);
txtArtist = new TextField();
txtTitle = new TextField();
txtArtist.setSize(WIDTH_TXT, HEIGHT_TXT);
txtTitle.setSize(WIDTH_TXT, HEIGHT_TXT);
chkClassical = new JCheckBox();
txtComposer = new TextField();
chkClassical.addActionListener(itemEvent -> {
txtComposer.setEditable(chkClassical.isSelected());
if (!chkClassical.isSelected()) {
txtComposer.setText("");
}
});
txtComposer.setSize(WIDTH_TXT, HEIGHT_TXT);
txtComposer.setEditable(model.getIsClassical());
apply = new JButton("Apply");
apply.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
saveToMod();
loadFromMod();
}
});
cancel = new JButton("Cancel");
cancel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
loadFromMod();
}
});
b2.add(txtArtist);
b2.add(txtTitle);
b2.add(chkClassical);
b2.add(txtComposer);
b2.add(apply);
b2.add(cancel);
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
frame.setBounds(LOCATION_X, LOCATION_Y, WIDTH, HEIGHT);
frame.setVisible(true);
| 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.publishMessage(new Message("High Message Priority", 1));
}
// run worker
var worker = new Worker(queueManager);
worker.run();
| 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 priority - o.priority;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
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()) {
return null;
}
final var root = queue[0];
queue[0] = queue[size - 1];
size--;
maxHeapifyDown();
return root;
}
/**
* Add message to queue.
*/
public void add(T t) {
ensureCapacity();
queue[size] = t;
size++;
maxHeapifyUp();
}
/**
* Check queue size.
*/
public boolean isEmpty() {
return size == 0;
}
private void maxHeapifyDown() {
var index = 0;
while (hasLeftChild(index)) {
var smallerIndex = leftChildIndex(index);
if (hasRightChild(index) && right(index).compareTo(left(index)) > 0) {
smallerIndex = rightChildIndex(index);
}
if (queue[index].compareTo(queue[smallerIndex]) > 0) {
break;
} else {
swap(index, smallerIndex);
}
index = smallerIndex;
}
}
private void maxHeapifyUp() {<FILL_FUNCTION_BODY>}
// index
private int parentIndex(int pos) {
return (pos - 1) / 2;
}
private int leftChildIndex(int parentPos) {
return 2 * parentPos + 1;
}
private int rightChildIndex(int parentPos) {
return 2 * parentPos + 2;
}
// value
private T parent(int childIndex) {
return queue[parentIndex(childIndex)];
}
private T left(int parentIndex) {
return queue[leftChildIndex(parentIndex)];
}
private T right(int parentIndex) {
return queue[rightChildIndex(parentIndex)];
}
// check
private boolean hasLeftChild(int index) {
return leftChildIndex(index) < size;
}
private boolean hasRightChild(int index) {
return rightChildIndex(index) < size;
}
private boolean hasParent(int index) {
return parentIndex(index) >= 0;
}
private void swap(int fpos, int tpos) {
var tmp = queue[fpos];
queue[fpos] = queue[tpos];
queue[tpos] = tmp;
}
private void ensureCapacity() {
if (size == capacity) {
capacity = capacity * 2;
queue = copyOf(queue, capacity);
}
}
/**
* For debug .. print current state of queue
*/
public void print() {
for (var i = 0; i <= size / 2; i++) {
LOGGER.info(" PARENT : " + queue[i] + " LEFT CHILD : "
+ left(i) + " RIGHT CHILD :" + right(i));
}
}
}
|
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.
*/
private void processMessage(Message message) {
LOGGER.info(message.toString());
}
}
|
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.numMeat = numMeat;
this.numPeppers = numPeppers;
}
/**
* Mix the stew.
*/
public void mix() {<FILL_FUNCTION_BODY>}
/**
* Taste the stew.
*/
public void taste() {
LOGGER.info("Tasting the stew");
if (numPotatoes > 0) {
numPotatoes--;
}
if (numCarrots > 0) {
numCarrots--;
}
if (numMeat > 0) {
numMeat--;
}
if (numPeppers > 0) {
numPeppers--;
}
}
}
|
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 (var i = 0; i < 3; i++) {
final var consumer = new Consumer("Consumer_" + i, queue);
executorService.submit(() -> {
while (true) {
consumer.consume();
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(10, TimeUnit.SECONDS);
executorService.shutdownNow();
} catch (InterruptedException e) {
LOGGER.error("Error waiting for ExecutorService shutdown");
}
| 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 = new CountDownLatch(2);
}
/**
* Program entry point.
*
* @param args arguments
* @throws InterruptedException if main thread is interrupted.
* @throws ExecutionException if an execution error occurs.
*/
public static void main(String[] args) throws InterruptedException {
var app = new App();
try {
app.promiseUsage();
} finally {
app.stop();
}
}
private void promiseUsage() {
calculateLineCount();
calculateLowestFrequencyChar();
}
/*
* Calculate the lowest frequency character and when that promise is fulfilled,
* consume the result in a Consumer<Character>
*/
private void calculateLowestFrequencyChar() {<FILL_FUNCTION_BODY>}
/*
* Calculate the line count and when that promise is fulfilled, consume the result
* in a Consumer<Integer>
*/
private void calculateLineCount() {
countLines().thenAccept(
count -> {
LOGGER.info("Line count is: {}", count);
taskCompleted();
}
);
}
/*
* Calculate the character frequency of a file and when that promise is fulfilled,
* then promise to apply function to calculate lowest character frequency.
*/
private Promise<Character> lowestFrequencyChar() {
return characterFrequency().thenApply(Utility::lowestFrequencyChar);
}
/*
* Download the file at DEFAULT_URL and when that promise is fulfilled,
* then promise to apply function to calculate character frequency.
*/
private Promise<Map<Character, Long>> characterFrequency() {
return download(DEFAULT_URL).thenApply(Utility::characterFrequency);
}
/*
* Download the file at DEFAULT_URL and when that promise is fulfilled,
* then promise to apply function to count lines in that file.
*/
private Promise<Integer> countLines() {
return download(DEFAULT_URL).thenApply(Utility::countLines);
}
/*
* Return a promise to provide the local absolute path of the file downloaded in background.
* This is an async method and does not wait until the file is downloaded.
*/
private Promise<String> download(String urlString) {
return new Promise<String>()
.fulfillInAsync(
() -> Utility.downloadFile(urlString), executor)
.onError(
throwable -> {
throwable.printStackTrace();
taskCompleted();
}
);
}
private void stop() throws InterruptedException {
stopLatch.await();
executor.shutdownNow();
}
private void taskCompleted() {
stopLatch.countDown();
}
}
|
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 = func;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
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 int COMPLETED,private static final int FAILED,private static final Logger LOGGER,private static final int RUNNING,private java.lang.Exception exception,private final non-sealed java.lang.Object lock,private volatile int state,private T value
|
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 = RUNNING;
private T value;
private Exception exception;
PromiseSupport() {
this.lock = new Object();
}
void fulfill(T value) {
this.value = value;
this.state = COMPLETED;
synchronized (lock) {
lock.notifyAll();
}
}
void fulfillExceptionally(Exception exception) {
this.exception = exception;
this.state = FAILED;
synchronized (lock) {
lock.notifyAll();
}
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return state > RUNNING;
}
@Override
public T get() throws InterruptedException, ExecutionException {
synchronized (lock) {
while (state == RUNNING) {
lock.wait();
}
}
if (state == COMPLETED) {
return value;
}
throw new ExecutionException(exception);
}
@Override
public T get(long timeout, TimeUnit unit) throws ExecutionException {<FILL_FUNCTION_BODY>}
}
|
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 value;
}
throw new ExecutionException(exception);
| 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 bufferedReader = new BufferedReader(new FileReader(fileLocation))) {
return bufferedReader.lines()
.flatMapToInt(String::chars)
.mapToObj(x -> (char) x)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
} catch (IOException ex) {
ex.printStackTrace();
}
return Collections.emptyMap();
}
/**
* Return the character with the lowest frequency, if exists.
*
* @return the character, {@code Optional.empty()} otherwise.
*/
public static Character lowestFrequencyChar(Map<Character, Long> charFrequency) {
return charFrequency
.entrySet()
.stream()
.min(Comparator.comparingLong(Entry::getValue))
.map(Entry::getKey)
.orElseThrow();
}
/**
* Count the number of lines in a file.
*
* @return number of lines, 0 if file does not exist.
*/
public static Integer countLines(String fileLocation) {
try (var bufferedReader = new BufferedReader(new FileReader(fileLocation))) {
return (int) bufferedReader.lines().count();
} catch (IOException ex) {
ex.printStackTrace();
}
return 0;
}
/**
* Downloads the contents from the given urlString, and stores it in a temporary directory.
*
* @return the absolute path of the file downloaded.
*/
public static String downloadFile(String urlString) throws IOException {<FILL_FUNCTION_BODY>}
}
|
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;
while ((line = bufferedReader.readLine()) != null) {
writer.write(line);
writer.write("\n");
}
LOGGER.info("File downloaded at: {}", file.getAbsolutePath());
return file.getAbsolutePath();
}
| 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);
mageProto.set(Stats.SPIRIT, 10);
var warProto = new Character(Type.WARRIOR, charProto);
warProto.set(Stats.RAGE, 15);
warProto.set(Stats.ARMOR, 15); // boost default armor for warrior
var rogueProto = new Character(Type.ROGUE, charProto);
rogueProto.set(Stats.ENERGY, 15);
rogueProto.set(Stats.AGILITY, 15); // boost default agility for rogue
/* usage */
var mag = new Character("Player_1", mageProto);
mag.set(Stats.ARMOR, 8);
LOGGER.info(mag.toString());
var warrior = new Character("Player_2", warProto);
LOGGER.info(warrior.toString());
var rogue = new Character("Player_3", rogueProto);
LOGGER.info(rogue.toString());
var rogueDouble = new Character("Player_4", rogue);
rogueDouble.set(Stats.ATTACK_POWER, 12);
LOGGER.info(rogueDouble.toString());
| 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.
*/
public Character() {
this.prototype = new Prototype() { // Null-value object
@Override
public Integer get(Stats stat) {
return null;
}
@Override
public boolean has(Stats stat) {
return false;
}
@Override
public void set(Stats stat, Integer val) {
// Does Nothing
}
@Override
public void remove(Stats stat) {
// Does Nothing.
}
};
}
public Character(Type type, Prototype prototype) {
this.type = type;
this.prototype = prototype;
}
/**
* Constructor.
*/
public Character(String name, Character prototype) {
this.name = name;
this.type = prototype.type;
this.prototype = prototype;
}
public String name() {
return name;
}
public Type type() {
return type;
}
@Override
public Integer get(Stats stat) {
var containsValue = properties.containsKey(stat);
if (containsValue) {
return properties.get(stat);
} else {
return prototype.get(stat);
}
}
@Override
public boolean has(Stats stat) {
return get(stat) != null;
}
@Override
public void set(Stats stat, Integer val) {
properties.put(stat, val);
}
@Override
public void remove(Stats stat) {
properties.put(stat, null);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
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 value = this.get(stat);
if (value == null) {
continue;
}
builder.append(" - ").append(stat.name()).append(':').append(value).append('\n');
}
return builder.toString();
| 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(warlord.toString());
LOGGER.info(beast.toString());
factory = new HeroFactoryImpl(
new OrcMage("axe"),
new OrcWarlord("sword"),
new OrcBeast("laser")
);
mage = factory.createMage();
warlord = factory.createWarlord();
beast = factory.createBeast();
LOGGER.info(mage.toString());
LOGGER.info(warlord.toString());
LOGGER.info(beast.toString());
| 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("Submitting TaskGenerators and ServiceExecutor threads.");
// Create three TaskGenerator threads. Each of them will submit different number of jobs.
final var taskRunnable1 = new TaskGenerator(msgQueue, 5);
final var taskRunnable2 = new TaskGenerator(msgQueue, 1);
final var taskRunnable3 = new TaskGenerator(msgQueue, 2);
// Create e service which should process the submitted jobs.
final var srvRunnable = new ServiceExecutor(msgQueue);
// Create a ThreadPool of 2 threads and
// submit all Runnable task for execution to executor..
executor = Executors.newFixedThreadPool(2);
executor.submit(taskRunnable1);
executor.submit(taskRunnable2);
executor.submit(taskRunnable3);
// submitting serviceExecutor thread to the Executor service.
executor.submit(srvRunnable);
// Initiates an orderly shutdown.
LOGGER.info("Initiating shutdown."
+ " Executor will shutdown only after all the Threads are completed.");
executor.shutdown();
// Wait for SHUTDOWN_TIME seconds for all the threads to complete
// their tasks and then shut down the executor and then exit.
if (!executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS)) {
LOGGER.info("Executor was shut down and Exiting.");
executor.shutdownNow();
}
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
| 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 Blocking
* Queue.
*/
public void submitMsg(Message msg) {<FILL_FUNCTION_BODY>}
/**
* All the messages will be retrieved by the ServiceExecutor by calling this method and process
* them. Retrieves and removes the head of this queue, or returns null if this queue is empty.
*/
public Message retrieveMsg() {
try {
return blkQueue.poll();
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
return null;
}
}
|
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(1000);
}
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
| 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 msgQueue, int msgCount) {
this.msgQueue = msgQueue;
this.msgCount = msgCount;
}
/**
* Submit messages to the Blocking Queue.
*/
public void submit(Message msg) {
try {
this.msgQueue.submitMsg(msg);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
/**
* Each TaskGenerator thread will submit all the messages to the Queue. After every message
* submission TaskGenerator thread will sleep for 1 second.
*/
public void run() {<FILL_FUNCTION_BODY>}
}
|
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 current thread to sleep after every Message submission.
Thread.sleep(1000);
}
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
| 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 be used to dispatch events.
*/
public App(Dispatcher dispatcher) {
this.dispatcher = dispatcher;
}
/**
* App entry.
*/
public static void main(String[] args) throws IOException {
new App(new ThreadPoolDispatcher(2)).start();
}
/**
* Starts the NIO reactor.
*
* @throws IOException if any channel fails to bind.
*/
public void start() throws IOException {<FILL_FUNCTION_BODY>}
/**
* Stops the NIO reactor. This is a blocking call.
*
* @throws InterruptedException if interrupted while stopping the reactor.
* @throws IOException if any I/O error occurs
*/
public void stop() throws InterruptedException, IOException {
reactor.stop();
dispatcher.stop();
for (var channel : channels) {
channel.getJavaChannel().close();
}
}
private AbstractNioChannel tcpChannel(int port, ChannelHandler handler) throws IOException {
var channel = new NioServerSocketChannel(port, handler);
channel.bind();
channels.add(channel);
return channel;
}
private AbstractNioChannel udpChannel(int port, ChannelHandler handler) throws IOException {
var channel = new NioDatagramChannel(port, handler);
channel.bind();
channels.add(channel);
return channel;
}
}
|
/*
* 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 loggingHandler = new LoggingHandler();
/*
* Our application binds to multiple channels and uses same logging handler to handle incoming
* log requests.
*/
reactor
.registerChannel(tcpChannel(16666, loggingHandler))
.registerChannel(tcpChannel(16667, loggingHandler))
.registerChannel(udpChannel(16668, loggingHandler))
.registerChannel(udpChannel(16669, loggingHandler))
.start();
| 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 will send logging requests.
* @throws UnknownHostException if localhost is unknown
*/
public UdpLoggingClient(String clientName, int port) throws UnknownHostException {
this.clientName = clientName;
this.remoteAddress = new InetSocketAddress(InetAddress.getLocalHost(), port);
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
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 data = new byte[1024];
var reply = new DatagramPacket(data, data.length);
socket.receive(reply);
if (reply.getLength() == 0) {
LOGGER.info("Read zero bytes");
} else {
LOGGER.info(new String(reply.getData(), 0, reply.getLength()));
}
artificialDelayOf(100);
}
} catch (IOException e1) {
LOGGER.error("error sending packets", e1);
}
| 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_FUNCTION_BODY>}
private static void sendReply(
AbstractNioChannel channel,
DatagramPacket incomingPacket,
SelectionKey key
) {
/*
* Create a reply acknowledgement datagram packet setting the receiver to the sender of incoming
* message.
*/
var replyPacket = new DatagramPacket(ByteBuffer.wrap(ACK));
replyPacket.setReceiver(incomingPacket.getSender());
channel.write(replyPacket, key);
}
private static void sendReply(AbstractNioChannel channel, SelectionKey key) {
var buffer = ByteBuffer.wrap(ACK);
channel.write(buffer, key);
}
private static void doLogging(ByteBuffer data) {
// assuming UTF-8 :(
LOGGER.info(new String(data.array(), 0, data.limit()));
}
}
|
/*
* 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, key);
} else if (readObject instanceof DatagramPacket) {
var datagram = (DatagramPacket) readObject;
doLogging(datagram.getData());
sendReply(channel, datagram, key);
} else {
throw new IllegalStateException("Unknown data received");
}
| 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 this channel.
* @param channel a NIO channel to be wrapped.
*/
public AbstractNioChannel(ChannelHandler handler, SelectableChannel channel) {
this.handler = handler;
this.channel = channel;
this.channelToPendingWrites = new ConcurrentHashMap<>();
}
/**
* Injects the reactor in this channel.
*/
void setReactor(NioReactor reactor) {
this.reactor = reactor;
}
/**
* Get channel.
*
* @return the wrapped NIO channel.
*/
public SelectableChannel getJavaChannel() {
return channel;
}
/**
* The operation in which the channel is interested, this operation is provided to {@link
* Selector}.
*
* @return interested operation.
* @see SelectionKey
*/
public abstract int getInterestedOps();
/**
* Binds the channel on provided port.
*
* @throws IOException if any I/O error occurs.
*/
public abstract void bind() throws IOException;
/**
* Reads the data using the key and returns the read data. The underlying channel should be
* fetched using {@link SelectionKey#channel()}.
*
* @param key the key on which read event occurred.
* @return data read.
* @throws IOException if any I/O error occurs.
*/
public abstract Object read(SelectionKey key) throws IOException;
/**
* Get handler.
*
* @return the handler associated with this channel.
*/
public ChannelHandler getHandler() {
return handler;
}
/*
* Called from the context of reactor thread when the key becomes writable. The channel writes the
* whole pending block of data at once.
*/
void flush(SelectionKey key) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Writes the data to the channel.
*
* @param pendingWrite the data to be written on channel.
* @param key the key which is writable.
* @throws IOException if any I/O error occurs.
*/
protected abstract void doWrite(Object pendingWrite, SelectionKey key) throws IOException;
/**
* Queues the data for writing. The data is not guaranteed to be written on underlying channel
* when this method returns. It will be written when the channel is flushed.
*
* <p>This method is used by the {@link ChannelHandler} to send reply back to the client. <br>
* Example:
*
* <pre>
* <code>
* {@literal @}Override
* public void handleChannelRead(AbstractNioChannel channel, Object readObj, SelectionKey key) {
* byte[] data = ((ByteBuffer)readObj).array();
* ByteBuffer buffer = ByteBuffer.wrap("Server reply".getBytes());
* channel.write(buffer, key);
* }
* </code>
* </pre>
*
* @param data the data to be written on underlying channel.
* @param key the key which is writable.
*/
public void write(Object data, SelectionKey key) {
var pendingWrites = this.channelToPendingWrites.get(key.channel());
if (pendingWrites == null) {
synchronized (this.channelToPendingWrites) {
pendingWrites = this.channelToPendingWrites.computeIfAbsent(key.channel(), k -> new ConcurrentLinkedQueue<>());
}
}
pendingWrites.add(data);
reactor.changeOps(key, SelectionKey.OP_WRITE);
}
}
|
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 write so channel is interested in reading more data
reactor.changeOps(key, SelectionKey.OP_READ);
| 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 should be called for
* binding the socket.
*
* @param port the port to be bound to listen for incoming datagram requests.
* @param handler the handler to be used for handling incoming requests on this channel.
* @throws IOException if any I/O error occurs.
*/
public NioDatagramChannel(int port, ChannelHandler handler) throws IOException {
super(handler, DatagramChannel.open());
this.port = port;
}
@Override
public int getInterestedOps() {
/*
* there is no need to accept connections in UDP, so the channel shows interest in reading data.
*/
return SelectionKey.OP_READ;
}
/**
* Reads and returns a {@link DatagramPacket} from the underlying channel.
*
* @return the datagram packet read having the sender address.
*/
@Override
public DatagramPacket read(SelectionKey key) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Get datagram channel.
*
* @return the underlying datagram channel.
*/
@Override
public DatagramChannel getJavaChannel() {
return (DatagramChannel) super.getJavaChannel();
}
/**
* Binds UDP socket on the provided <code>port</code>.
*
* @throws IOException if any I/O error occurs.
*/
@Override
public void bind() throws IOException {
getJavaChannel().socket().bind(new InetSocketAddress(InetAddress.getLocalHost(), port));
getJavaChannel().configureBlocking(false);
LOGGER.info("Bound UDP socket at port: {}", port);
}
/**
* Writes the pending {@link DatagramPacket} to the underlying channel sending data to the
* intended receiver of the packet.
*/
@Override
protected void doWrite(Object pendingWrite, SelectionKey key) throws IOException {
var pendingPacket = (DatagramPacket) pendingWrite;
getJavaChannel().send(pendingPacket.getData(), pendingPacket.getReceiver());
}
/**
* Writes the outgoing {@link DatagramPacket} to the channel. The intended receiver of the
* datagram packet must be set in the <code>data</code> using {@link
* DatagramPacket#setReceiver(SocketAddress)}.
*/
@Override
public void write(Object data, SelectionKey key) {
super.write(data, key);
}
/**
* Container of data used for {@link NioDatagramChannel} to communicate with remote peer.
*/
public static class DatagramPacket {
private SocketAddress sender;
private final ByteBuffer data;
private SocketAddress receiver;
/**
* Creates a container with underlying data.
*
* @param data the underlying message to be written on channel.
*/
public DatagramPacket(ByteBuffer data) {
this.data = data;
}
/**
* Get sender address.
*
* @return the sender address.
*/
public SocketAddress getSender() {
return sender;
}
/**
* Sets the sender address of this packet.
*
* @param sender the sender address.
*/
public void setSender(SocketAddress sender) {
this.sender = sender;
}
/**
* Get receiver address.
*
* @return the receiver address.
*/
public SocketAddress getReceiver() {
return receiver;
}
/**
* Sets the intended receiver address. This must be set when writing to the channel.
*
* @param receiver the receiver address.
*/
public void setReceiver(SocketAddress receiver) {
this.receiver = receiver;
}
/**
* Get data.
*
* @return the underlying message that will be written on channel.
*/
public ByteBuffer getData() {
return data;
}
}
}
|
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 DatagramPacket(buffer);
packet.setSender(sender);
return packet;
| 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 getJavaChannel() ,public abstract java.lang.Object read(java.nio.channels.SelectionKey) throws java.io.IOException,public void write(java.lang.Object, java.nio.channels.SelectionKey) <variables>private final non-sealed java.nio.channels.SelectableChannel channel,private final non-sealed Map<java.nio.channels.SelectableChannel,Queue<java.lang.Object>> channelToPendingWrites,private final non-sealed com.iluwatar.reactor.framework.ChannelHandler handler,private com.iluwatar.reactor.framework.NioReactor reactor
|
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, a new command is added in the command queue and then the event loop picks up
* the command and executes it in next iteration.
*/
private final Queue<Runnable> pendingCommands = new ConcurrentLinkedQueue<>();
private final ExecutorService reactorMain = Executors.newSingleThreadExecutor();
/**
* Creates a reactor which will use provided {@code dispatcher} to dispatch events. The
* application can provide various implementations of dispatcher which suits its needs.
*
* @param dispatcher a non-null dispatcher used to dispatch events on registered channels.
* @throws IOException if any I/O error occurs.
*/
public NioReactor(Dispatcher dispatcher) throws IOException {
this.dispatcher = dispatcher;
this.selector = Selector.open();
}
/**
* Starts the reactor event loop in a new thread.
*/
public void start() {<FILL_FUNCTION_BODY>}
/**
* Stops the reactor and related resources such as dispatcher.
*
* @throws InterruptedException if interrupted while stopping the reactor.
* @throws IOException if any I/O error occurs.
*/
public void stop() throws InterruptedException, IOException {
reactorMain.shutdown();
selector.wakeup();
if (!reactorMain.awaitTermination(4, TimeUnit.SECONDS)) {
reactorMain.shutdownNow();
}
selector.close();
LOGGER.info("Reactor stopped");
}
/**
* Registers a new channel (handle) with this reactor. Reactor will start waiting for events on
* this channel and notify of any events. While registering the channel the reactor uses {@link
* AbstractNioChannel#getInterestedOps()} to know about the interested operation of this channel.
*
* @param channel a new channel on which reactor will wait for events. The channel must be bound
* prior to being registered.
* @return this
* @throws IOException if any I/O error occurs.
*/
public NioReactor registerChannel(AbstractNioChannel channel) throws IOException {
var key = channel.getJavaChannel().register(selector, channel.getInterestedOps());
key.attach(channel);
channel.setReactor(this);
return this;
}
private void eventLoop() throws IOException {
// honor interrupt request
while (!Thread.interrupted()) {
// honor any pending commands first
processPendingCommands();
/*
* Synchronous event de-multiplexing happens here, this is blocking call which returns when it
* is possible to initiate non-blocking operation on any of the registered channels.
*/
selector.select();
/*
* Represents the events that have occurred on registered handles.
*/
var keys = selector.selectedKeys();
var iterator = keys.iterator();
while (iterator.hasNext()) {
var key = iterator.next();
if (!key.isValid()) {
iterator.remove();
continue;
}
processKey(key);
}
keys.clear();
}
}
private void processPendingCommands() {
var iterator = pendingCommands.iterator();
while (iterator.hasNext()) {
var command = iterator.next();
command.run();
iterator.remove();
}
}
/*
* Initiation dispatcher logic, it checks the type of event and notifier application specific
* event handler to handle the event.
*/
private void processKey(SelectionKey key) throws IOException {
if (key.isAcceptable()) {
onChannelAcceptable(key);
} else if (key.isReadable()) {
onChannelReadable(key);
} else if (key.isWritable()) {
onChannelWritable(key);
}
}
private static void onChannelWritable(SelectionKey key) throws IOException {
var channel = (AbstractNioChannel) key.attachment();
channel.flush(key);
}
private void onChannelReadable(SelectionKey key) {
try {
// reads the incoming data in context of reactor main loop. Can this be improved?
var readObject = ((AbstractNioChannel) key.attachment()).read(key);
dispatchReadEvent(key, readObject);
} catch (IOException e) {
try {
key.channel().close();
} catch (IOException e1) {
LOGGER.error("error closing channel", e1);
}
}
}
/*
* Uses the application provided dispatcher to dispatch events to application handler.
*/
private void dispatchReadEvent(SelectionKey key, Object readObject) {
dispatcher.onChannelReadEvent((AbstractNioChannel) key.attachment(), readObject, key);
}
private void onChannelAcceptable(SelectionKey key) throws IOException {
var serverSocketChannel = (ServerSocketChannel) key.channel();
var socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
var readKey = socketChannel.register(selector, SelectionKey.OP_READ);
readKey.attach(key.attachment());
}
/**
* Queues the change of operations request of a channel, which will change the interested
* operations of the channel sometime in the future.
*
* <p>This is a non-blocking method and does not guarantee that the operations have changed when
* this method returns.
*
* @param key the key for which operations have to be changed.
* @param interestedOps the new interest operations.
*/
public void changeOps(SelectionKey key, int interestedOps) {
pendingCommands.add(new ChangeKeyOpsCommand(key, interestedOps));
selector.wakeup();
}
/**
* A command that changes the interested operations of the key provided.
*/
static class ChangeKeyOpsCommand implements Runnable {
private final SelectionKey key;
private final int interestedOps;
public ChangeKeyOpsCommand(SelectionKey key, int interestedOps) {
this.key = key;
this.interestedOps = interestedOps;
}
public void run() {
key.interestOps(interestedOps);
}
@Override
public String toString() {
return "Change of ops to: " + interestedOps;
}
}
}
|
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 readObject, SelectionKey key) {<FILL_FUNCTION_BODY>}
/**
* No resources to free.
*/
@Override
public void stop() {
// no-op
}
}
|
/*
* 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));
}
LOGGER.info("Writers added...");
// Start readers
for (var i = 0; i < 5; i++) {
var readingTime = ThreadLocalRandom.current().nextLong(10);
executeService.submit(new Reader("Reader " + i, lock.readLock(), readingTime));
}
LOGGER.info("Readers added...");
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
LOGGER.error("Error sleeping before adding more readers", e);
Thread.currentThread().interrupt();
}
// Start readers
for (var i = 6; i < 10; i++) {
var readingTime = ThreadLocalRandom.current().nextLong(10);
executeService.submit(new Reader("Reader " + i, lock.readLock(), readingTime));
}
LOGGER.info("More readers added...");
// In the system console, it can see that the read operations are executed concurrently while
// write operations are exclusive.
executeService.shutdown();
try {
executeService.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOGGER.error("Error waiting for ExecutorService shutdown", e);
Thread.currentThread().interrupt();
}
| 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 (in milliseconds) for this reader to engage reading
*/
public Reader(String name, Lock readLock, long readingTime) {
this.name = name;
this.readLock = readLock;
this.readingTime = readingTime;
}
/**
* Create new Reader who reads for 250ms.
*
* @param name - Name of the thread owning the reader
* @param readLock - Lock for this reader
*/
public Reader(String name, Lock readLock) {
this(name, readLock, 250L);
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
/**
* Simulate the read operation.
*/
public void read() throws InterruptedException {
LOGGER.info("{} begin", name);
Thread.sleep(readingTime);
LOGGER.info("{} finish after reading {}ms", name, readingTime);
}
}
|
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 readers. Make sure no
* writers currently owns the lock.
*/
private void acquireForReaders() {
// Try to get the globalMutex lock for the first reader
synchronized (globalMutex) {
// If the no one get the lock or the lock is locked by reader, just set the reference
// to the globalMutex to indicate that the lock is locked by Reader.
while (doesWriterOwnThisLock()) {
try {
globalMutex.wait();
} catch (InterruptedException e) {
var message = "InterruptedException while waiting for globalMutex in acquireForReaders";
LOGGER.info(message, e);
Thread.currentThread().interrupt();
}
}
globalMutex.add(this);
}
}
@Override
public void unlock() {<FILL_FUNCTION_BODY>}
@Override
public void lockInterruptibly() {
throw new UnsupportedOperationException();
}
@Override
public boolean tryLock() {
throw new UnsupportedOperationException();
}
@Override
public boolean tryLock(long time, TimeUnit unit) {
throw new UnsupportedOperationException();
}
@Override
public Condition newCondition() {
throw new UnsupportedOperationException();
}
}
|
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, mostly the writer
globalMutex.remove(this);
globalMutex.notifyAll();
}
}
}
| 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(String name, Lock writeLock) {
this(name, writeLock, 250L);
}
/**
* Create new Writer.
*
* @param name - Name of the thread owning the writer
* @param writeLock - Lock for this writer
* @param writingTime - amount of time (in milliseconds) for this reader to engage writing
*/
public Writer(String name, Lock writeLock, long writingTime) {
this.name = name;
this.writeLock = writeLock;
this.writingTime = writingTime;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
/**
* Simulate the write operation.
*/
public void write() throws InterruptedException {
LOGGER.info("{} begin", name);
Thread.sleep(writingTime);
LOGGER.info("{} finished after writing {}ms", name, writingTime);
}
}
|
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("Julia {}", customerRegistry.getCustomer("2"));
| 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 Person("Terry", "Law", 36);
// Add new Person records
repository.save(peter);
repository.save(nasta);
repository.save(john);
repository.save(terry);
// Count Person records
LOGGER.info("Count Person records: {}", repository.count());
// Print all records
var persons = (List<Person>) repository.findAll();
persons.stream().map(Person::toString).forEach(LOGGER::info);
// Update Person
nasta.setName("Barbora");
nasta.setSurname("Spotakova");
repository.save(nasta);
repository.findById(2L).ifPresent(p -> LOGGER.info("Find by id 2: {}", p));
// Remove record from Person
repository.deleteById(2L);
// count records
LOGGER.info("Count Person records: {}", repository.count());
// find by name
repository
.findOne(new PersonSpecifications.NameEqualSpec("John"))
.ifPresent(p -> LOGGER.info("Find by John is {}", p));
// find by age
persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40));
LOGGER.info("Find Person with age between 20,40: ");
persons.stream().map(Person::toString).forEach(LOGGER::info);
repository.deleteAll();
context.close();
| 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:databases-person");
basicDataSource.setUsername("sa");
basicDataSource.setPassword("sa");
return basicDataSource;
}
/**
* Factory to create a especific instance of Entity Manager.
*/
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
var entityManager = new LocalContainerEntityManagerFactoryBean();
entityManager.setDataSource(dataSource());
entityManager.setPackagesToScan("com.iluwatar");
entityManager.setPersistenceProvider(new HibernatePersistenceProvider());
entityManager.setJpaProperties(jpaProperties());
return entityManager;
}
/**
* Properties for Jpa.
*/
private static Properties jpaProperties() {
var properties = new Properties();
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
return properties;
}
/**
* Get transaction manager.
*/
@Bean
public JpaTransactionManager transactionManager() {
var transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
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("Terry", "Law", 36);
// Add new Person records
repository.save(peter);
repository.save(nasta);
repository.save(john);
repository.save(terry);
// Count Person records
LOGGER.info("Count Person records: {}", repository.count());
// Print all records
var persons = (List<Person>) repository.findAll();
persons.stream().map(Person::toString).forEach(LOGGER::info);
// Update Person
nasta.setName("Barbora");
nasta.setSurname("Spotakova");
repository.save(nasta);
repository.findById(2L).ifPresent(p -> LOGGER.info("Find by id 2: {}", p));
// Remove record from Person
repository.deleteById(2L);
// count records
LOGGER.info("Count Person records: {}", repository.count());
// find by name
repository
.findOne(new PersonSpecifications.NameEqualSpec("John"))
.ifPresent(p -> LOGGER.info("Find by John is {}", p));
// find by age
persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40));
LOGGER.info("Find Person with age between 20,40: ");
persons.stream().map(Person::toString).forEach(LOGGER::info);
context.close();
| 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[] args) throws Exception {
noErrors();
errorNoRetry();
errorWithRetry();
errorWithRetryExponentialBackoff();
}
private static void noErrors() throws Exception {
op = new FindCustomer("123");
op.perform();
LOG.info("Sometimes the operation executes with no errors.");
}
private static void errorNoRetry() throws Exception {
op = new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND));
try {
op.perform();
} catch (CustomerNotFoundException e) {
LOG.info("Yet the operation will throw an error every once in a while.");
}
}
private static void errorWithRetry() throws Exception {<FILL_FUNCTION_BODY>}
private static void errorWithRetryExponentialBackoff() throws Exception {
final var retry = new RetryExponentialBackoff<>(
new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)),
6, //6 attempts
30000, //30 s max delay between attempts
e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass())
);
op = retry;
final var customerId = op.perform();
LOG.info(String.format(
"However, retrying the operation while ignoring a recoverable error will eventually yield "
+ "the result %s after a number of attempts %s", customerId, retry.attempts()
));
}
}
|
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();
LOG.info(String.format(
"However, retrying the operation while ignoring a recoverable error will eventually yield "
+ "the result %s after a number of attempts %s", customerId, retry.attempts()
));
| 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 the {@link BusinessOperation} to retry
* @param maxAttempts number of times to retry
* @param delay delay (in milliseconds) between attempts
* @param ignoreTests tests to check whether the remote exception can be ignored. No exceptions
* will be ignored if no tests are given
*/
@SafeVarargs
public Retry(
BusinessOperation<T> op,
int maxAttempts,
long delay,
Predicate<Exception>... ignoreTests
) {
this.op = op;
this.maxAttempts = maxAttempts;
this.delay = delay;
this.attempts = new AtomicInteger();
this.test = Arrays.stream(ignoreTests).reduce(Predicate::or).orElse(e -> false);
this.errors = new ArrayList<>();
}
/**
* The errors encountered while retrying, in the encounter order.
*
* @return the errors encountered while retrying
*/
public List<Exception> errors() {
return Collections.unmodifiableList(this.errors);
}
/**
* The number of retries performed.
*
* @return the number of retries performed
*/
public int attempts() {
return this.attempts.intValue();
}
@Override
public T perform() throws BusinessException {<FILL_FUNCTION_BODY>}
}
|
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 (InterruptedException f) {
//ignore
}
}
} while (true);
| 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 final List<Exception> errors;
/**
* Ctor.
*
* @param op the {@link BusinessOperation} to retry
* @param maxAttempts number of times to retry
* @param ignoreTests tests to check whether the remote exception can be ignored. No exceptions
* will be ignored if no tests are given
*/
@SafeVarargs
public RetryExponentialBackoff(
BusinessOperation<T> op,
int maxAttempts,
long maxDelay,
Predicate<Exception>... ignoreTests
) {
this.op = op;
this.maxAttempts = maxAttempts;
this.maxDelay = maxDelay;
this.attempts = new AtomicInteger();
this.test = Arrays.stream(ignoreTests).reduce(Predicate::or).orElse(e -> false);
this.errors = new ArrayList<>();
}
/**
* The errors encountered while retrying, in the encounter order.
*
* @return the errors encountered while retrying
*/
public List<Exception> errors() {
return Collections.unmodifiableList(this.errors);
}
/**
* The number of retries performed.
*
* @return the number of retries performed
*/
public int attempts() {
return this.attempts.intValue();
}
@Override
public T perform() throws BusinessException {<FILL_FUNCTION_BODY>}
}
|
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()) * 1000 + RANDOM.nextInt(1000);
var delay = Math.min(testDelay, this.maxDelay);
Thread.sleep(delay);
} catch (InterruptedException f) {
//ignore
}
}
} while (true);
| 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(" customer has an investor role - {}", hasInvestorRole);
customer.getRole(Investor, InvestorRole.class)
.ifPresent(inv -> {
inv.setAmountToInvest(1000);
inv.setName("Billy");
});
customer.getRole(Borrower, BorrowerRole.class)
.ifPresent(inv -> inv.setName("Johny"));
customer.getRole(Investor, InvestorRole.class)
.map(InvestorRole::invest)
.ifPresent(LOGGER::info);
customer.getRole(Borrower, BorrowerRole.class)
.map(BorrowerRole::borrow)
.ifPresent(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;
})
.orElse(false);
}
@Override
public boolean hasRole(Role role) {
return roles.containsKey(role);
}
@Override
public boolean remRole(Role role) {
return Objects.nonNull(roles.remove(role));
}
@Override
public <T extends Customer> Optional<T> getRole(Role role, Class<T> expectedRole) {
return Optional
.ofNullable(roles.get(role))
.filter(expectedRole::isInstance)
.map(expectedRole::cast);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
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 transient com.iluwatar.roleobject.Customer newCustomer(com.iluwatar.roleobject.Role[]) ,public abstract boolean remRole(com.iluwatar.roleobject.Role) <variables>
|
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 amountToInvest) {
this.amountToInvest = amountToInvest;
}
public String invest() {<FILL_FUNCTION_BODY>}
}
|
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() {<FILL_FUNCTION_BODY>}
/**
* add chapter to saga.
*
* @param name chapter name
* @return this
*/
public Saga chapter(String name) {
this.chapters.add(new Chapter(name));
return this;
}
/**
* set value to last chapter.
*
* @param value invalue
* @return this
*/
public Saga setInValue(Object value) {
if (chapters.isEmpty()) {
return this;
}
chapters.get(chapters.size() - 1).setInValue(value);
return this;
}
/**
* get value from current chapter.
*
* @return value
*/
public Object getCurrentValue() {
return chapters.get(pos).getInValue();
}
/**
* set value to current chapter.
*
* @param value to set
*/
public void setCurrentValue(Object value) {
chapters.get(pos).setInValue(value);
}
/**
* set status for current chapter.
*
* @param result to set
*/
public void setCurrentStatus(ChapterResult result) {
chapters.get(pos).setResult(result);
}
void setFinished(boolean finished) {
this.finished = finished;
}
boolean isForward() {
return forward;
}
int forward() {
return ++pos;
}
int back() {
this.forward = false;
return --pos;
}
private Saga() {
this.chapters = new ArrayList<>();
this.pos = 0;
this.forward = true;
this.finished = false;
}
Chapter getCurrent() {
return chapters.get(pos);
}
boolean isPresent() {
return pos >= 0 && pos < chapters.size();
}
boolean isCurrentSuccess() {
return chapters.get(pos).isSuccess();
}
/**
* Class presents a chapter status and incoming parameters(incoming parameter transforms to
* outcoming parameter).
*/
public static class Chapter {
private final String name;
private ChapterResult result;
private Object inValue;
public Chapter(String name) {
this.name = name;
this.result = ChapterResult.INIT;
}
public Object getInValue() {
return inValue;
}
public void setInValue(Object object) {
this.inValue = object;
}
public String getName() {
return name;
}
/**
* set result.
*
* @param result {@link ChapterResult}
*/
public void setResult(ChapterResult result) {
this.result = result;
}
/**
* the result for chapter is good.
*
* @return true if is good otherwise bad
*/
public boolean isSuccess() {
return result == ChapterResult.SUCCESS;
}
}
/**
* result for chapter.
*/
public enum ChapterResult {
INIT, SUCCESS, ROLLBACK
}
/**
* result for saga.
*/
public enum SagaResult {
PROGRESS, FINISHED, ROLLBACKED
}
@Override
public String toString() {
return "Saga{"
+ "chapters="
+ Arrays.toString(chapters.toArray())
+ ", pos="
+ pos
+ ", forward="
+ forward
+ '}';
}
}
|
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: goodOrder is {}, badOrder is {}",
goodOrderSaga.getResult(), badOrderSaga.getResult());
}
private static Saga newSaga(Object value) {<FILL_FUNCTION_BODY>}
private static ServiceDiscoveryService serviceDiscovery() {
var sd = new ServiceDiscoveryService();
return sd
.discover(new OrderService(sd))
.discover(new FlyBookingService(sd))
.discover(new HotelBookingService(sd))
.discover(new WithdrawMoneyService(sd));
}
}
|
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 = saga;
Object nextVal;
var chapterName = saga.getCurrent().getName();
if (chapterName.equals(getName())) {
if (saga.isForward()) {
nextSaga = process(saga);
nextVal = nextSaga.getCurrentValue();
if (nextSaga.isCurrentSuccess()) {
nextSaga.forward();
} else {
nextSaga.back();
}
} else {
nextSaga = rollback(saga);
nextVal = nextSaga.getCurrentValue();
nextSaga.back();
}
if (isSagaFinished(nextSaga)) {
return nextSaga;
}
nextSaga.setCurrentValue(nextVal);
}
var finalNextSaga = nextSaga;
return sd.find(chapterName).map(ch -> ch.execute(finalNextSaga))
.orElseThrow(serviceNotFoundException(chapterName));
}
private Supplier<RuntimeException> serviceNotFoundException(String chServiceName) {
return () -> new RuntimeException(
String.format("the service %s has not been found", chServiceName));
}
@Override
public Saga process(Saga saga) {
var inValue = saga.getCurrentValue();
LOGGER.info("The chapter '{}' has been started. "
+ "The data {} has been stored or calculated successfully",
getName(), inValue);
saga.setCurrentStatus(Saga.ChapterResult.SUCCESS);
saga.setCurrentValue(inValue);
return saga;
}
@Override
public Saga rollback(Saga saga) {
var inValue = saga.getCurrentValue();
LOGGER.info("The Rollback for a chapter '{}' has been started. "
+ "The data {} has been rollbacked successfully",
getName(), inValue);
saga.setCurrentStatus(Saga.ChapterResult.ROLLBACK);
saga.setCurrentValue(inValue);
return saga;
}
private boolean isSagaFinished(Saga saga) {<FILL_FUNCTION_BODY>}
}
|
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);
return saga;
}
return super.process(saga);
| 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.iluwatar.saga.choreography.Saga) <variables>protected static final Logger LOGGER,private final non-sealed com.iluwatar.saga.choreography.ServiceDiscoveryService sd
|
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 been started. "
+ "The data {} has been rollbacked successfully",
getName(), value);
return super.rollback(value);
| 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("bad_order");
Saga.Result crashedOrder = sagaOrchestrator.execute("crashed_order");
LOGGER.info("orders: goodOrder is {}, badOrder is {},crashedOrder is {}",
goodOrder, badOrder, crashedOrder);
}
private static Saga newSaga() {
return Saga
.create()
.chapter("init an order")
.chapter("booking a Fly")
.chapter("booking a Hotel")
.chapter("withdrawing Money");
}
private static ServiceDiscoveryService serviceDiscovery() {<FILL_FUNCTION_BODY>}
}
|
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 SagaOrchestrator(Saga saga, ServiceDiscoveryService sd) {
this.saga = saga;
this.sd = sd;
this.state = new CurrentState();
}
/**
* pipeline to execute saga process/story.
*
* @param value incoming value
* @param <K> type for incoming value
* @return result @see {@link Result}
*/
@SuppressWarnings("unchecked")
public <K> Result execute(K value) {<FILL_FUNCTION_BODY>}
private static class CurrentState {
int currentNumber;
boolean isForward;
void cleanUp() {
currentNumber = 0;
isForward = true;
}
CurrentState() {
this.currentNumber = 0;
this.isForward = true;
}
boolean isForward() {
return isForward;
}
void directionToBack() {
isForward = false;
}
int forward() {
return ++currentNumber;
}
int back() {
return --currentNumber;
}
int current() {
return currentNumber;
}
}
}
|
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();
state.back();
continue;
}
var srv = srvOpt.get();
if (state.isForward()) {
var processRes = srv.process(tempVal);
if (processRes.isSuccess()) {
next = state.forward();
tempVal = (K) processRes.getValue();
} else {
state.directionToBack();
}
} else {
var rlRes = srv.rollback(tempVal);
if (rlRes.isSuccess()) {
next = state.back();
tempVal = (K) rlRes.getValue();
} else {
result = CRASHED;
next = state.back();
}
}
if (!saga.isPresent(next)) {
return state.isForward() ? FINISHED : result == CRASHED ? CRASHED : ROLLBACK;
}
}
| 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 Rollback for a chapter '{}' has been started. "
+ "The data {} has been rollbacked successfully",
getName(), value);
return ChapterResult.success(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 generator with product cost as 50 and domestic product tax
var domesticProductInvoice = new InvoiceGenerator(PRODUCT_COST, new DomesticTaxCalculator());
LOGGER.info("Domestic Tax applied: {}", "" + domesticProductInvoice.getAmountWithTax());
| 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, ClassNotFoundException {<FILL_FUNCTION_BODY>}
private static void deleteSchema(DataSource dataSource) {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(CountrySchemaSql.DELETE_SCHEMA_SQL);
} catch (SQLException e) {
LOGGER.info("Exception thrown " + e.getMessage());
}
}
private static void createSchema(DataSource dataSource) {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(CountrySchemaSql.CREATE_SCHEMA_SQL);
} catch (SQLException e) {
LOGGER.info("Exception thrown " + e.getMessage());
}
}
private static DataSource createDataSource() {
var dataSource = new JdbcDataSource();
dataSource.setURL(DB_URL);
return dataSource;
}
}
|
final var dataSource = createDataSource();
deleteSchema(dataSource);
createSchema(dataSource);
// Initializing Country Object China
final var China = new Country(
86,
"China",
"Asia",
"Chinese"
);
// Initializing Country Object UnitedArabEmirates
final var UnitedArabEmirates = new Country(
971,
"United Arab Emirates",
"Asia",
"Arabic"
);
// Initializing CountrySchemaSql Object with parameter "China" and "dataSource"
final var serializedChina = new CountrySchemaSql(China, dataSource);
// Initializing CountrySchemaSql Object with parameter "UnitedArabEmirates" and "dataSource"
final var serializedUnitedArabEmirates = new CountrySchemaSql(UnitedArabEmirates, dataSource);
/*
By using CountrySchemaSql.insertCountry() method, the private (Country) type variable within Object
CountrySchemaSql will be serialized to a set of bytes and persist to database.
For more details of CountrySchemaSql.insertCountry() method please refer to CountrySchemaSql.java file
*/
serializedChina.insertCountry();
serializedUnitedArabEmirates.insertCountry();
/*
By using CountrySchemaSql.selectCountry() method, CountrySchemaSql object will read the sets of bytes from database
and deserialize it to Country object.
For more details of CountrySchemaSql.selectCountry() method please refer to CountrySchemaSql.java file
*/
serializedChina.selectCountry();
serializedUnitedArabEmirates.selectCountry();
| 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;
/**
* Public constructor.
*
* @param dataSource datasource
* @param country country
*/
public CountrySchemaSql(Country country, DataSource dataSource) {
this.country = new Country(
country.getCode(),
country.getName(),
country.getContinents(),
country.getLanguage()
);
this.dataSource = dataSource;
}
/**
* This method will serialize a Country object and store it to database.
* @return int type, if successfully insert a serialized object to database then return country code, else return -1.
* @throws IOException if any.
*/
@Override
public int insertCountry() throws IOException {
var sql = "INSERT INTO WORLD (ID, COUNTRY) VALUES (?, ?)";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oss = new ObjectOutputStream(baos)) {
oss.writeObject(country);
oss.flush();
preparedStatement.setInt(1, country.getCode());
preparedStatement.setBlob(2, new ByteArrayInputStream(baos.toByteArray()));
preparedStatement.execute();
return country.getCode();
} catch (SQLException e) {
LOGGER.info("Exception thrown " + e.getMessage());
}
return -1;
}
/**
* This method will select a data item from database and deserialize it.
* @return int type, if successfully select and deserialized object from database then return country code,
* else return -1.
* @throws IOException if any.
* @throws ClassNotFoundException if any.
*/
@Override
public int selectCountry() throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>}
}
|
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.next()) {
Blob countryBlob = rs.getBlob("country");
ByteArrayInputStream baos = new ByteArrayInputStream(countryBlob.getBytes(1, (int) countryBlob.length()));
ObjectInputStream ois = new ObjectInputStream(baos);
country = (Country) ois.readObject();
LOGGER.info("Country: " + country);
}
return rs.getInt("id");
}
} catch (SQLException e) {
LOGGER.info("Exception thrown " + e.getMessage());
}
return -1;
| 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 Actions for variable scenarios.
*/
public static void scenario(Servant servant, int compliment) {<FILL_FUNCTION_BODY>}
}
|
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.forEach(Royalty::changeMood);
// check your luck
if (servant.checkIfYouWillBeHanged(guests)) {
LOGGER.info("{} will live another day", servant.name);
} else {
LOGGER.info("Poor {}. His days are numbered", servant.name);
}
| 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 receiveCompliments() {
complimentReceived = true;
}
@Override
public void changeMood() {<FILL_FUNCTION_BODY>}
@Override
public boolean getMood() {
return isHappy;
}
}
|
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;
}
public void receiveCompliments() {
complimentReceived = true;
}
@Override
public void changeMood() {<FILL_FUNCTION_BODY>}
@Override
public boolean getMood() {
return isHappy;
}
public void setFlirtiness(boolean f) {
this.isFlirty = f;
}
}
|
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 args arguments
* @throws IOException ex
*/
public static void main(String[] args) throws IOException {
// Create HTTP server listening on port 8000
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
// Set up session management endpoints
server.createContext("/login", new LoginHandler(sessions, sessionCreationTimes));
server.createContext("/logout", new LogoutHandler(sessions, sessionCreationTimes));
// Start the server
server.start();
// Start background task to check for expired sessions
sessionExpirationTask();
LOGGER.info("Server started. Listening on port 8080...");
}
private static void sessionExpirationTask() {<FILL_FUNCTION_BODY>}
}
|
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 (sessionCreationTimes) {
Iterator<Map.Entry<String, Instant>> iterator =
sessionCreationTimes.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Instant> entry = iterator.next();
if (entry.getValue().plusMillis(SESSION_EXPIRATION_TIME).isBefore(currentTime)) {
sessions.remove(entry.getKey());
iterator.remove();
}
}
}
}
LOGGER.info("Session expiration checker finished!");
} catch (InterruptedException e) {
LOGGER.error("An error occurred: ", e);
Thread.currentThread().interrupt();
}
}
}).start();
| 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;
}
@Override
public void handle(HttpExchange exchange) {<FILL_FUNCTION_BODY>}
}
|
// 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 " + sessionCreationTimes.get(sessionId));
// Set session ID as cookie
exchange.getResponseHeaders().add("Set-Cookie", "sessionID=" + sessionId);
// Send response
String response = "Login successful!\n" + "Session ID: " + sessionId;
try {
exchange.sendResponseHeaders(200, response.length());
} catch (IOException e) {
LOGGER.error("An error occurred: ", e);
}
try (OutputStream os = exchange.getResponseBody()) {
os.write(response.getBytes());
} catch (IOException e) {
LOGGER.error("An error occurred: ", e);
}
| 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 = sessionCreationTimes;
}
@Override
public void handle(HttpExchange exchange) {<FILL_FUNCTION_BODY>}
}
|
// 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 += "Session has already expired!";
} else {
response = "Logout successful!\n" + "Session ID: " + currentSessionId;
}
//Remove session
if (currentSessionId != null) {
LOGGER.info("User " + sessions.get(currentSessionId) + " deleted!");
} else {
LOGGER.info("User already deleted!");
}
sessions.remove(sessionId);
sessionCreationTimes.remove(sessionId);
try {
exchange.sendResponseHeaders(200, response.length());
} catch (IOException e) {
LOGGER.error("An error has occurred: ", e);
}
try (OutputStream os = exchange.getResponseBody()) {
os.write(response.getBytes());
} catch (IOException e) {
LOGGER.error("An error has occurred: ", e);
}
| 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();
}
/**
* Initialize data.
*/
public static void initData() {<FILL_FUNCTION_BODY>}
/**
* Query the data.
*/
public static void queryData() {
var wizardDao = new WizardDaoImpl();
var spellbookDao = new SpellbookDaoImpl();
var spellDao = new SpellDaoImpl();
var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao);
LOGGER.info("Enumerating all wizards");
service.findAllWizards().stream().map(Wizard::getName).forEach(LOGGER::info);
LOGGER.info("Enumerating all spellbooks");
service.findAllSpellbooks().stream().map(Spellbook::getName).forEach(LOGGER::info);
LOGGER.info("Enumerating all spells");
service.findAllSpells().stream().map(Spell::getName).forEach(LOGGER::info);
LOGGER.info("Find wizards with spellbook 'Book of Idores'");
var wizardsWithSpellbook = service.findWizardsWithSpellbook(BOOK_OF_IDORES);
wizardsWithSpellbook.forEach(w -> LOGGER.info("{} has 'Book of Idores'", w.getName()));
LOGGER.info("Find wizards with spell 'Fireball'");
var wizardsWithSpell = service.findWizardsWithSpell("Fireball");
wizardsWithSpell.forEach(w -> LOGGER.info("{} has 'Fireball'", w.getName()));
}
}
|
// 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 spell8 = new Spell("Rock armour");
var spell9 = new Spell("Light");
var spell10 = new Spell("Bee swarm");
var spell11 = new Spell("Haste");
var spell12 = new Spell("Levitation");
var spell13 = new Spell("Magic lock");
var spell14 = new Spell("Summon hell bat");
var spell15 = new Spell("Water walking");
var spell16 = new Spell("Magic storm");
var spell17 = new Spell("Entangle");
var spellDao = new SpellDaoImpl();
spellDao.persist(spell1);
spellDao.persist(spell2);
spellDao.persist(spell3);
spellDao.persist(spell4);
spellDao.persist(spell5);
spellDao.persist(spell6);
spellDao.persist(spell7);
spellDao.persist(spell8);
spellDao.persist(spell9);
spellDao.persist(spell10);
spellDao.persist(spell11);
spellDao.persist(spell12);
spellDao.persist(spell13);
spellDao.persist(spell14);
spellDao.persist(spell15);
spellDao.persist(spell16);
spellDao.persist(spell17);
// spellbooks
var spellbookDao = new SpellbookDaoImpl();
var spellbook1 = new Spellbook("Book of Orgymon");
spellbookDao.persist(spellbook1);
spellbook1.addSpell(spell1);
spellbook1.addSpell(spell2);
spellbook1.addSpell(spell3);
spellbook1.addSpell(spell4);
spellbookDao.merge(spellbook1);
var spellbook2 = new Spellbook("Book of Aras");
spellbookDao.persist(spellbook2);
spellbook2.addSpell(spell5);
spellbook2.addSpell(spell6);
spellbookDao.merge(spellbook2);
var spellbook3 = new Spellbook("Book of Kritior");
spellbookDao.persist(spellbook3);
spellbook3.addSpell(spell7);
spellbook3.addSpell(spell8);
spellbook3.addSpell(spell9);
spellbookDao.merge(spellbook3);
var spellbook4 = new Spellbook("Book of Tamaex");
spellbookDao.persist(spellbook4);
spellbook4.addSpell(spell10);
spellbook4.addSpell(spell11);
spellbook4.addSpell(spell12);
spellbookDao.merge(spellbook4);
var spellbook5 = new Spellbook(BOOK_OF_IDORES);
spellbookDao.persist(spellbook5);
spellbook5.addSpell(spell13);
spellbookDao.merge(spellbook5);
var spellbook6 = new Spellbook("Book of Opaen");
spellbookDao.persist(spellbook6);
spellbook6.addSpell(spell14);
spellbook6.addSpell(spell15);
spellbookDao.merge(spellbook6);
var spellbook7 = new Spellbook("Book of Kihione");
spellbookDao.persist(spellbook7);
spellbook7.addSpell(spell16);
spellbook7.addSpell(spell17);
spellbookDao.merge(spellbook7);
// wizards
var wizardDao = new WizardDaoImpl();
var wizard1 = new Wizard("Aderlard Boud");
wizardDao.persist(wizard1);
wizard1.addSpellbook(spellbookDao.findByName("Book of Orgymon"));
wizard1.addSpellbook(spellbookDao.findByName("Book of Aras"));
wizardDao.merge(wizard1);
var wizard2 = new Wizard("Anaxis Bajraktari");
wizardDao.persist(wizard2);
wizard2.addSpellbook(spellbookDao.findByName("Book of Kritior"));
wizard2.addSpellbook(spellbookDao.findByName("Book of Tamaex"));
wizardDao.merge(wizard2);
var wizard3 = new Wizard("Xuban Munoa");
wizardDao.persist(wizard3);
wizard3.addSpellbook(spellbookDao.findByName(BOOK_OF_IDORES));
wizard3.addSpellbook(spellbookDao.findByName("Book of Opaen"));
wizardDao.merge(wizard3);
var wizard4 = new Wizard("Blasius Dehooge");
wizardDao.persist(wizard4);
wizard4.addSpellbook(spellbookDao.findByName("Book of Kihione"));
wizardDao.merge(wizard4);
| 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 responsibility
* of the caller to open as well as close the session (prevents potential resource leak).
*/
protected SessionFactory getSessionFactory() {
return HibernateUtil.getSessionFactory();
}
@Override
public E find(Long id) {
Transaction tx = null;
E result;
try (var session = getSessionFactory().openSession()) {
tx = session.beginTransaction();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<E> builderQuery = criteriaBuilder.createQuery(persistentClass);
Root<E> root = builderQuery.from(persistentClass);
builderQuery.select(root).where(criteriaBuilder.equal(root.get("id"), id));
Query<E> query = session.createQuery(builderQuery);
result = query.uniqueResult();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
}
return result;
}
@Override
public void persist(E entity) {
Transaction tx = null;
try (var session = getSessionFactory().openSession()) {
tx = session.beginTransaction();
session.persist(entity);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
}
}
@Override
public E merge(E entity) {<FILL_FUNCTION_BODY>}
@Override
public void delete(E entity) {
Transaction tx = null;
try (var session = getSessionFactory().openSession()) {
tx = session.beginTransaction();
session.delete(entity);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
}
}
@Override
public List<E> findAll() {
Transaction tx = null;
List<E> result;
try (var session = getSessionFactory().openSession()) {
tx = session.beginTransaction();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<E> builderQuery = criteriaBuilder.createQuery(persistentClass);
Root<E> root = builderQuery.from(persistentClass);
builderQuery.select(root);
Query<E> query = session.createQuery(builderQuery);
result = query.getResultList();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
}
return result;
}
}
|
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;
}
return result;
| 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 synchronized SessionFactory getSessionFactory() {<FILL_FUNCTION_BODY>}
/**
* Drop the current connection, resulting in a create-drop clean database next time. This is
* mainly used for JUnit testing since one test should not influence the other
*/
public static void dropSession() {
getSessionFactory().close();
sessionFactory = null;
}
}
|
if (sessionFactory == null) {
try {
sessionFactory = new Configuration()
.addAnnotatedClass(Wizard.class)
.addAnnotatedClass(Spellbook.class)
.addAnnotatedClass(Spell.class)
.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
.setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1")
.setProperty("hibernate.current_session_context_class", "thread")
.setProperty("hibernate.show_sql", "false")
.setProperty("hibernate.hbm2ddl.auto", "create-drop").buildSessionFactory();
} catch (Throwable ex) {
LOGGER.error("Initial SessionFactory creation failed.", ex);
throw new ExceptionInInitializerError(ex);
}
}
return sessionFactory;
| 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 = wizardDao;
this.spellbookDao = spellbookDao;
this.spellDao = spellDao;
}
@Override
public List<Wizard> findAllWizards() {
return wizardDao.findAll();
}
@Override
public List<Spellbook> findAllSpellbooks() {
return spellbookDao.findAll();
}
@Override
public List<Spell> findAllSpells() {
return spellDao.findAll();
}
@Override
public List<Wizard> findWizardsWithSpellbook(String name) {
var spellbook = spellbookDao.findByName(name);
return new ArrayList<>(spellbook.getWizards());
}
@Override
public List<Wizard> findWizardsWithSpell(String name) {<FILL_FUNCTION_BODY>}
}
|
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> root = builderQuery.from(Spell.class);
builderQuery.select(root).where(criteriaBuilder.equal(root.get("name"), name));
Query<Spell> query = session.createQuery(builderQuery);
result = query.uniqueResult();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
}
return result;
| 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) ,public void persist(com.iluwatar.servicelayer.spell.Spell) <variables>protected Class<com.iluwatar.servicelayer.spell.Spell> persistentClass
|
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);
Root<Spellbook> root = builderQuery.from(Spellbook.class);
builderQuery.select(root).where(criteriaBuilder.equal(root.get("name"), name));
Query<Spellbook> query = session.createQuery(builderQuery);
result = query.uniqueResult();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
}
return result;
| 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.iluwatar.servicelayer.spellbook.Spellbook) ,public void persist(com.iluwatar.servicelayer.spellbook.Spellbook) <variables>protected Class<com.iluwatar.servicelayer.spellbook.Spellbook> persistentClass
|
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> root = builderQuery.from(Wizard.class);
builderQuery.select(root).where(criteriaBuilder.equal(root.get("name"), name));
Query<Wizard> query = session.createQuery(builderQuery);
result = query.uniqueResult();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
}
return result;
| 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.wizard.Wizard) ,public void persist(com.iluwatar.servicelayer.wizard.Wizard) <variables>protected Class<com.iluwatar.servicelayer.wizard.Wizard> persistentClass
|
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.execute();
| 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 ServiceImpl("jndi/serviceB");
} else {
return null;
}
| 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 getService(String serviceName) {<FILL_FUNCTION_BODY>}
/**
* Adds the service into the cache map.
*
* @param newService a {@link Service}
*/
public void addService(Service newService) {
serviceCache.put(newService.getName(), newService);
}
}
|
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(Math.random() * 1000) + 1;
}
@Override
public String getName() {
return serviceName;
}
@Override
public int getId() {
return id;
}
@Override
public void execute() {<FILL_FUNCTION_BODY>}
}
|
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 into the cache map
* for future requests.
*
* @param serviceJndiName a string
* @return {@link Service}
*/
public static Service getService(String serviceJndiName) {<FILL_FUNCTION_BODY>}
}
|
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();
serviceObj = (Service) ctx.lookup(serviceJndiName);
if (serviceObj != null) { // Only cache a service if it actually exists
serviceCache.addService(serviceObj);
}
return serviceObj;
}
| 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 view = new GiantView();
var dispatcher = new Dispatcher(view);
dispatcher.addAction(action1);
dispatcher.addAction(action2);
var controller = new GiantController(dispatcher);
// initial display
controller.updateView(giant1);
controller.updateView(giant2);
// controller receives some interactions that affect the giant
controller.setCommand(new Command(Fatigue.SLEEPING, Health.HEALTHY, Nourishment.STARVING), 0);
controller.setCommand(new Command(Fatigue.ALERT, Health.HEALTHY, Nourishment.HUNGRY), 1);
// redisplay
controller.updateView(giant1);
controller.updateView(giant2);
// controller receives some interactions that affect the giant
| 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
*/
GiantModel(String name, Health health, Fatigue fatigue, Nourishment nourishment) {
this.name = name;
this.model = new com.iluwatar.model.view.controller.GiantModel(health, fatigue,
nourishment);
}
/**
* Gets health.
*
* @return the health
*/
Health getHealth() {
return model.getHealth();
}
/**
* Sets health.
*
* @param health the health
*/
void setHealth(Health health) {
model.setHealth(health);
}
/**
* Gets fatigue.
*
* @return the fatigue
*/
Fatigue getFatigue() {
return model.getFatigue();
}
void setFatigue(Fatigue fatigue) {
model.setFatigue(fatigue);
}
/**
* Gets nourishment.
*
* @return the nourishment
*/
Nourishment getNourishment() {
return model.getNourishment();
}
/**
* Sets nourishment.
*
* @param nourishment the nourishment
*/
void setNourishment(Nourishment nourishment) {
model.setNourishment(nourishment);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
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 = new Shard(3);
var manager = new LookupShardManager();
manager.addNewShard(shard1);
manager.addNewShard(shard2);
manager.addNewShard(shard3);
manager.storeData(data1);
manager.storeData(data2);
manager.storeData(data3);
manager.storeData(data4);
shard1.clearData();
shard2.clearData();
shard3.clearData();
var rangeShardManager = new RangeShardManager();
rangeShardManager.addNewShard(shard1);
rangeShardManager.addNewShard(shard2);
rangeShardManager.addNewShard(shard3);
rangeShardManager.storeData(data1);
rangeShardManager.storeData(data2);
rangeShardManager.storeData(data3);
rangeShardManager.storeData(data4);
shard1.clearData();
shard2.clearData();
shard3.clearData();
var hashShardManager = new HashShardManager();
hashShardManager.addNewShard(shard1);
hashShardManager.addNewShard(shard2);
hashShardManager.addNewShard(shard3);
hashShardManager.storeData(data1);
hashShardManager.storeData(data2);
hashShardManager.storeData(data3);
hashShardManager.storeData(data4);
shard1.clearData();
shard2.clearData();
shard3.clearData();
| 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 = value;
this.type = type;
}
public int getKey() {
return key;
}
public void setKey(final int key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(final String value) {
this.value = value;
}
public DataType getType() {
return type;
}
public void setType(DataType type) {
this.type = type;
}
enum DataType {
TYPE_1, TYPE_2, TYPE_3
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
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 int allocateShard(Data data) {<FILL_FUNCTION_BODY>}
}
|
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);
LOGGER.info(data.toString() + " is stored in Shard " + shardId);
return shardId;
}
@Override
protected int allocateShard(Data data) {<FILL_FUNCTION_BODY>}
}
|
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 -> -1;
};
}
}
|
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 shardId is already existed.
*/
public boolean addNewShard(final Shard shard) {
var shardId = shard.getId();
if (!shardMap.containsKey(shardId)) {
shardMap.put(shardId, shard);
return true;
} else {
return false;
}
}
/**
* Remove a shard instance by provided Id.
*
* @param shardId Id of shard instance to remove.
* @return {@code true} if removed. {@code false} if the shardId is not existed.
*/
public boolean removeShardById(final int shardId) {<FILL_FUNCTION_BODY>}
/**
* Get shard instance by provided shardId.
*
* @param shardId id of shard instance to get
* @return required shard instance
*/
public Shard getShardById(final int shardId) {
return shardMap.get(shardId);
}
/**
* Store data in proper shard instance.
*
* @param data new data
* @return id of shard that the data is stored in
*/
public abstract int storeData(final Data data);
/**
* Allocate proper shard to provided data.
*
* @param data new data
* @return id of shard that the data should be stored
*/
protected abstract int allocateShard(final Data data);
}
|
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 main(String[] args) {
SpringApplication.run(SingleTableInheritance.class, args);
}
/**
* The starting point of the CommandLineRunner
* where the main program is run.
*
* @param args program runtime arguments
*/
@Override
public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
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);
// Saving Truck to DB as a Vehicle
Vehicle vehicle2 = new Truck("Ford", "F-150", 3325, 14000);
Vehicle truck1 = vehicleService.saveVehicle(vehicle2);
log.info("Vehicle 2 saved : {}\n", truck1);
log.info("Fetching Vehicles :- ");
// Fetching the Car from DB
Car savedCar1 = (Car) vehicleService.getVehicle(vehicle1.getVehicleId());
log.info("Fetching Car1 from DB : {}", savedCar1);
// Fetching the Truck from DB
Truck savedTruck1 = (Truck) vehicleService.getVehicle(vehicle2.getVehicleId());
log.info("Fetching Truck1 from DB : {}\n", savedTruck1);
log.info("Fetching All Vehicles :- ");
// Fetching the Vehicles present in the DB
List<Vehicle> allVehiclesFromDb = vehicleService.getAllVehicles();
allVehiclesFromDb.forEach(s -> log.info(s.toString()));
| 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 object
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
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
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
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.