proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
iluwatar_java-design-patterns
java-design-patterns/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java
Inventory
addItem
class Inventory { private final int inventorySize; private final List<Item> items; private final Lock lock; /** * Constructor. */ public Inventory(int inventorySize) { this.inventorySize = inventorySize; this.items = new ArrayList<>(inventorySize); this.lock = new ReentrantLock(); } /** * Add item. */ public boolean addItem(Item item) {<FILL_FUNCTION_BODY>} /** * Get all the items in the inventory. * * @return All the items of the inventory, as an unmodifiable list */ public final List<Item> getItems() { return List.copyOf(items); } }
if (items.size() < inventorySize) { lock.lock(); try { if (items.size() < inventorySize) { items.add(item); var thread = Thread.currentThread(); LOGGER.info("{}: items.size()={}, inventorySize={}", thread, items.size(), inventorySize); return true; } } finally { lock.unlock(); } } return false;
202
117
319
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java
App
main
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// initialize game objects and print their status var objects = List.of( new FlamingAsteroid(0, 0, 5, 5), new SpaceStationMir(1, 1, 2, 2), new Meteoroid(10, 10, 15, 15), new SpaceStationIss(12, 12, 14, 14) ); objects.forEach(o -> LOGGER.info(o.toString())); LOGGER.info(""); // collision check objects.forEach(o1 -> objects.forEach(o2 -> { if (o1 != o2 && o1.intersectsWith(o2)) { o1.collision(o2); } })); LOGGER.info(""); // output eventual object statuses objects.forEach(o -> LOGGER.info(o.toString())); LOGGER.info("");
56
244
300
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java
GameObject
toString
class GameObject extends Rectangle { private boolean damaged; private boolean onFire; public GameObject(int left, int top, int right, int bottom) { super(left, top, right, bottom); } @Override public String toString() {<FILL_FUNCTION_BODY>} public abstract void collision(GameObject gameObject); public abstract void collisionResolve(FlamingAsteroid asteroid); public abstract void collisionResolve(Meteoroid meteoroid); public abstract void collisionResolve(SpaceStationMir mir); public abstract void collisionResolve(SpaceStationIss iss); }
return String.format("%s at %s damaged=%b onFire=%b", this.getClass().getSimpleName(), super.toString(), isDamaged(), isOnFire());
165
48
213
<methods>public non-sealed void <init>() ,public java.lang.String toString() <variables>private final non-sealed int bottom,private final non-sealed int left,private final non-sealed int right,private final non-sealed int top
iluwatar_java-design-patterns
java-design-patterns/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java
Rectangle
intersectsWith
class Rectangle { private final int left; private final int top; private final int right; private final int bottom; boolean intersectsWith(Rectangle r) {<FILL_FUNCTION_BODY>} @Override public String toString() { return String.format("[%d,%d,%d,%d]", getLeft(), getTop(), getRight(), getBottom()); } }
return !(r.getLeft() > getRight() || r.getRight() < getLeft() || r.getTop() > getBottom() || r .getBottom() < getTop());
111
49
160
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java
SpaceStationMir
collisionResolve
class SpaceStationMir extends GameObject { public SpaceStationMir(int left, int top, int right, int bottom) { super(left, top, right, bottom); } @Override public void collision(GameObject gameObject) { gameObject.collisionResolve(this); } @Override public void collisionResolve(FlamingAsteroid asteroid) { LOGGER.info(AppConstants.HITS + " {} is damaged! {} is set on fire!", asteroid.getClass() .getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass() .getSimpleName()); setDamaged(true); setOnFire(true); } @Override public void collisionResolve(Meteoroid meteoroid) { LOGGER.info(AppConstants.HITS + " {} is damaged!", meteoroid.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName()); setDamaged(true); } @Override public void collisionResolve(SpaceStationMir mir) { LOGGER.info(AppConstants.HITS + " {} is damaged!", mir.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName()); setDamaged(true); } @Override public void collisionResolve(SpaceStationIss iss) {<FILL_FUNCTION_BODY>} }
LOGGER.info(AppConstants.HITS, " {} is damaged!", iss.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName()); setDamaged(true);
392
61
453
<methods>public void <init>(int, int, int, int) ,public abstract void collision(com.iluwatar.doubledispatch.GameObject) ,public abstract void collisionResolve(com.iluwatar.doubledispatch.FlamingAsteroid) ,public abstract void collisionResolve(com.iluwatar.doubledispatch.Meteoroid) ,public abstract void collisionResolve(com.iluwatar.doubledispatch.SpaceStationMir) ,public abstract void collisionResolve(com.iluwatar.doubledispatch.SpaceStationIss) ,public java.lang.String toString() <variables>private boolean damaged,private boolean onFire
iluwatar_java-design-patterns
java-design-patterns/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumInvocationHandler.java
AlbumInvocationHandler
invoke
class AlbumInvocationHandler implements InvocationHandler { private TinyRestClient restClient; /** * Class constructor. It instantiates a TinyRestClient object. * * @param baseUrl Root url for endpoints. * @param httpClient Handle the http communication. */ public AlbumInvocationHandler(String baseUrl, HttpClient httpClient) { this.restClient = new TinyRestClient(baseUrl, httpClient); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {<FILL_FUNCTION_BODY>} }
LOGGER.info("===== Calling the method {}.{}()", method.getDeclaringClass().getSimpleName(), method.getName()); return restClient.send(method, args);
158
52
210
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/App.java
App
callMethods
class App { static final String REST_API_URL = "https://jsonplaceholder.typicode.com"; private String baseUrl; private HttpClient httpClient; private AlbumService albumServiceProxy; /** * Class constructor. * * @param baseUrl Root url for endpoints. * @param httpClient Handle the http communication. */ public App(String baseUrl, HttpClient httpClient) { this.baseUrl = baseUrl; this.httpClient = httpClient; } /** * Application entry point. * * @param args External arguments to be passed. Optional. */ public static void main(String[] args) { App app = new App(App.REST_API_URL, HttpClient.newHttpClient()); app.createDynamicProxy(); app.callMethods(); } /** * Create the Dynamic Proxy linked to the AlbumService interface and to the AlbumInvocationHandler. */ public void createDynamicProxy() { AlbumInvocationHandler albumInvocationHandler = new AlbumInvocationHandler(baseUrl, httpClient); albumServiceProxy = (AlbumService) Proxy.newProxyInstance( App.class.getClassLoader(), new Class<?>[]{AlbumService.class}, albumInvocationHandler); } /** * Call the methods of the Dynamic Proxy, in other words, the AlbumService interface's methods * and receive the responses from the Rest API. */ public void callMethods() {<FILL_FUNCTION_BODY>} }
int albumId = 17; int userId = 3; var albums = albumServiceProxy.readAlbums(); albums.forEach(album -> LOGGER.info("{}", album)); var album = albumServiceProxy.readAlbum(albumId); LOGGER.info("{}", album); var newAlbum = albumServiceProxy.createAlbum(Album.builder() .title("Big World").userId(userId).build()); LOGGER.info("{}", newAlbum); var editAlbum = albumServiceProxy.updateAlbum(albumId, Album.builder() .title("Green Valley").userId(userId).build()); LOGGER.info("{}", editAlbum); var removedAlbum = albumServiceProxy.deleteAlbum(albumId); LOGGER.info("{}", removedAlbum);
404
222
626
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/JsonUtil.java
JsonUtil
jsonToObject
class JsonUtil { private static ObjectMapper objectMapper = new ObjectMapper(); private JsonUtil() { } /** * Convert an object to a Json string representation. * * @param object Object to convert. * @param <T> Object's class. * @return Json string. */ public static <T> String objectToJson(T object) { try { return objectMapper.writeValueAsString(object); } catch (JsonProcessingException e) { LOGGER.error("Cannot convert the object " + object + " to Json.", e); return null; } } /** * Convert a Json string to an object of a class. * * @param json Json string to convert. * @param clazz Object's class. * @param <T> Object's generic class. * @return Object. */ public static <T> T jsonToObject(String json, Class<T> clazz) {<FILL_FUNCTION_BODY>} /** * Convert a Json string to a List of objects of a class. * * @param json Json string to convert. * @param clazz Object's class. * @param <T> Object's generic class. * @return List of objects. */ public static <T> List<T> jsonToList(String json, Class<T> clazz) { try { CollectionType listType = objectMapper.getTypeFactory() .constructCollectionType(ArrayList.class, clazz); return objectMapper.reader().forType(listType).readValue(json); } catch (JsonProcessingException e) { LOGGER.error("Cannot convert the Json " + json + " to List of " + clazz.getName() + ".", e); return List.of(); } } }
try { return objectMapper.readValue(json, clazz); } catch (IOException e) { LOGGER.error("Cannot convert the Json " + json + " to class " + clazz.getName() + ".", e); return null; }
476
68
544
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/TinyRestClient.java
TinyRestClient
getResponse
class TinyRestClient { private static Map<Method, Annotation> httpAnnotationByMethod = new HashMap<>(); private String baseUrl; private HttpClient httpClient; /** * Class constructor. * * @param baseUrl Root url for endpoints. * @param httpClient Handle the http communication. */ public TinyRestClient(String baseUrl, HttpClient httpClient) { this.baseUrl = baseUrl; this.httpClient = httpClient; } /** * Creates a http communication to request and receive data from an endpoint. * * @param method Interface's method which is annotated with a http method. * @param args Method's arguments passed in the call. * @return Response from the endpoint. * @throws IOException Exception thrown when any fail happens in the call. * @throws InterruptedException Exception thrown when call is interrupted. */ public Object send(Method method, Object[] args) throws IOException, InterruptedException { var httpAnnotation = getHttpAnnotation(method); if (httpAnnotation == null) { return null; } var httpAnnotationName = httpAnnotation.annotationType().getSimpleName().toUpperCase(); var url = baseUrl + buildUrl(method, args, httpAnnotation); var bodyPublisher = buildBodyPublisher(method, args); var httpRequest = HttpRequest.newBuilder() .uri(URI.create(url)) .header("Content-Type", "application/json") .method(httpAnnotationName, bodyPublisher) .build(); var httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); var statusCode = httpResponse.statusCode(); if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) { var errorDetail = httpResponse.body(); LOGGER.error("Error from server: " + errorDetail); return null; } return getResponse(method, httpResponse); } private String buildUrl(Method method, Object[] args, Annotation httpMethodAnnotation) { var url = annotationValue(httpMethodAnnotation); if (url == null) { return ""; } var index = 0; for (var parameter : method.getParameters()) { var pathAnnotation = getAnnotationOf(parameter.getDeclaredAnnotations(), Path.class); if (pathAnnotation != null) { var pathParam = "{" + annotationValue(pathAnnotation) + "}"; var pathValue = UriUtils.encodePath(args[index].toString(), StandardCharsets.UTF_8); url = url.replace(pathParam, pathValue); } index++; } return url; } private HttpRequest.BodyPublisher buildBodyPublisher(Method method, Object[] args) { var index = 0; for (var parameter : method.getParameters()) { var bodyAnnotation = getAnnotationOf(parameter.getDeclaredAnnotations(), Body.class); if (bodyAnnotation != null) { var body = JsonUtil.objectToJson(args[index]); return HttpRequest.BodyPublishers.ofString(body); } index++; } return HttpRequest.BodyPublishers.noBody(); } private Object getResponse(Method method, HttpResponse<String> httpResponse) {<FILL_FUNCTION_BODY>} private Annotation getHttpAnnotation(Method method) { return httpAnnotationByMethod.computeIfAbsent(method, m -> Arrays.stream(m.getDeclaredAnnotations()) .filter(annot -> annot.annotationType().isAnnotationPresent(Http.class)) .findFirst().orElse(null)); } private Annotation getAnnotationOf(Annotation[] annotations, Class<?> clazz) { return Arrays.stream(annotations) .filter(annot -> annot.annotationType().equals(clazz)) .findFirst().orElse(null); } private String annotationValue(Annotation annotation) { var valueMethod = Arrays.stream(annotation.annotationType().getDeclaredMethods()) .filter(methodAnnot -> methodAnnot.getName().equals("value")) .findFirst().orElse(null); if (valueMethod == null) { return null; } Object result; try { result = valueMethod.invoke(annotation, (Object[]) null); } catch (Exception e) { LOGGER.error("Cannot read the value " + annotation.annotationType().getSimpleName() + "." + valueMethod.getName() + "()", e); result = null; } return (result instanceof String strResult ? strResult : null); } }
var rawData = httpResponse.body(); Type returnType = null; try { returnType = method.getGenericReturnType(); } catch (Exception e) { LOGGER.error("Cannot get the generic return type of the method " + method.getName() + "()"); return null; } if (returnType instanceof ParameterizedType) { Class<?> responseClass = (Class<?>) (((ParameterizedType) returnType) .getActualTypeArguments()[0]); return JsonUtil.jsonToList(rawData, responseClass); } else { Class<?> responseClass = method.getReturnType(); return JsonUtil.jsonToObject(rawData, responseClass); }
1,183
184
1,367
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/embedded-value/src/main/java/com/iluwatar/embedded/value/App.java
App
main
class App { /** * Program entry point. * * @param args command line args. * @throws Exception if any error occurs. * */ public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
final var dataSource = new DataSource(); // Orders to insert into database final var order1 = new Order("JBL headphone", "Ram", new ShippingAddress("Bangalore", "Karnataka", "560040")); final var order2 = new Order("MacBook Pro", "Manjunath", new ShippingAddress("Bangalore", "Karnataka", "581204")); final var order3 = new Order("Carrie Soto is Back", "Shiva", new ShippingAddress("Bangalore", "Karnataka", "560004")); // Create table for orders - Orders(id, name, orderedBy, city, state, pincode). // We can see that table is different from the Order object we have. // We're mapping ShippingAddress into city, state, pincode columns of the database and not creating a separate table. if (dataSource.createSchema()) { LOGGER.info("TABLE CREATED"); LOGGER.info("Table \"Orders\" schema:\n" + dataSource.getSchema()); } else { //If not able to create table, there's nothing we can do further. LOGGER.error("Error creating table"); System.exit(0); } // Initially, database is empty LOGGER.info("Orders Query: {}", dataSource.queryOrders().toList()); //Insert orders where shippingAddress is mapped to different columns of the same table dataSource.insertOrder(order1); dataSource.insertOrder(order2); dataSource.insertOrder(order3); // Query orders. // We'll create ShippingAddress object from city, state, pincode values from the table and add it to Order object LOGGER.info("Orders Query: {}", dataSource.queryOrders().toList() + "\n"); //Query order by given id LOGGER.info("Query Order with id=2: {}", dataSource.queryOrder(2)); //Remove order by given id. //Since we'd mapped address in the same table, deleting order will also take out the shipping address details. LOGGER.info("Remove Order with id=1"); dataSource.removeOrder(1); LOGGER.info("\nOrders Query: {}", dataSource.queryOrders().toList() + "\n"); //After successful demonstration of the pattern, drop the table if (dataSource.deleteSchema()) { LOGGER.info("TABLE DROPPED"); } else { //If there's a potential error while dropping table LOGGER.error("Error deleting table"); }
75
669
744
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSource.java
DataSource
removeOrder
class DataSource implements DataSourceInterface { private Connection conn; // Statements are objects which are used to execute queries which will not be repeated. private Statement getschema; private Statement deleteschema; private Statement queryOrders; // PreparedStatements are used to execute queries which will be repeated. private PreparedStatement insertIntoOrders; private PreparedStatement removeorder; private PreparedStatement queyOrderById; /** * {@summary Establish connection to database. * Constructor to create DataSource object.} */ public DataSource() { try { conn = DriverManager.getConnection(JDBC_URL); LOGGER.info("Connected to H2 in-memory database: " + conn.getCatalog()); } catch (SQLException e) { LOGGER.error(e.getLocalizedMessage(), e.getCause()); } } @Override public boolean createSchema() { try (Statement createschema = conn.createStatement()) { createschema.execute(CREATE_SCHEMA); insertIntoOrders = conn.prepareStatement(INSERT_ORDER, PreparedStatement.RETURN_GENERATED_KEYS); getschema = conn.createStatement(); queryOrders = conn.createStatement(); removeorder = conn.prepareStatement(REMOVE_ORDER); queyOrderById = conn.prepareStatement(QUERY_ORDER); deleteschema = conn.createStatement(); } catch (SQLException e) { LOGGER.error(e.getLocalizedMessage(), e.getCause()); return false; } return true; } @Override public String getSchema() { try { var resultSet = getschema.executeQuery(GET_SCHEMA); var sb = new StringBuilder(); while (resultSet.next()) { sb.append("Col name: ").append(resultSet.getString(1)).append(", Col type: ").append(resultSet.getString(2)).append("\n"); } getschema.close(); return sb.toString(); } catch (Exception e) { LOGGER.error("Error in retrieving schema: {}", e.getLocalizedMessage(), e.getCause()); } return "Schema unavailable"; } @Override public boolean insertOrder(Order order) { try { conn.setAutoCommit(false); insertIntoOrders.setString(1, order.getItem()); insertIntoOrders.setString(2, order.getOrderedBy()); var address = order.getShippingAddress(); insertIntoOrders.setString(3, address.getCity()); insertIntoOrders.setString(4, address.getState()); insertIntoOrders.setString(5, address.getPincode()); var affectedRows = insertIntoOrders.executeUpdate(); if (affectedRows == 1) { var rs = insertIntoOrders.getGeneratedKeys(); rs.last(); var insertedAddress = new ShippingAddress(address.getCity(), address.getState(), address.getPincode()); var insertedOrder = new Order(rs.getInt(1), order.getItem(), order.getOrderedBy(), insertedAddress); conn.commit(); LOGGER.info("Inserted: {}", insertedOrder); } else { conn.rollback(); } } catch (Exception e) { LOGGER.error(e.getLocalizedMessage()); } finally { try { conn.setAutoCommit(true); } catch (SQLException e) { LOGGER.error(e.getLocalizedMessage()); } } return true; } @Override public Stream<Order> queryOrders() { var ordersList = new ArrayList<Order>(); try (var rSet = queryOrders.executeQuery(QUERY_ORDERS)) { while (rSet.next()) { var order = new Order(rSet.getInt(1), rSet.getString(2), rSet.getString(3), new ShippingAddress(rSet.getString(4), rSet.getString(5), rSet.getString(6))); ordersList.add(order); } rSet.close(); } catch (SQLException e) { LOGGER.error(e.getMessage(), e.getCause()); } return ordersList.stream(); } /** * Query order by given id. * @param id as the parameter * @return Order objct * @throws SQLException in case of unexpected events */ @Override public Order queryOrder(int id) throws SQLException { Order order = null; queyOrderById.setInt(1, id); try (var rSet = queyOrderById.executeQuery()) { queyOrderById.setInt(1, id); if (rSet.next()) { var address = new ShippingAddress(rSet.getString(4), rSet.getString(5), rSet.getString(6)); order = new Order(rSet.getInt(1), rSet.getString(2), rSet.getString(3), address); } rSet.close(); } catch (Exception e) { LOGGER.error(e.getLocalizedMessage(), e.getCause()); } return order; } @Override public void removeOrder(int id) throws Exception {<FILL_FUNCTION_BODY>} @Override public boolean deleteSchema() throws Exception { try { deleteschema.execute(DELETE_SCHEMA); queryOrders.close(); queyOrderById.close(); deleteschema.close(); insertIntoOrders.close(); conn.close(); return true; } catch (Exception e) { LOGGER.error(e.getLocalizedMessage(), e.getCause()); } return false; } }
try { conn.setAutoCommit(false); removeorder.setInt(1, id); if (removeorder.executeUpdate() == 1) { LOGGER.info("Order with id " + id + " successfully removed"); } else { LOGGER.info("Order with id " + id + " unavailable."); } } catch (Exception e) { LOGGER.error(e.getLocalizedMessage(), e.getCause()); conn.rollback(); } finally { conn.setAutoCommit(true); }
1,522
143
1,665
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java
App
main
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
var kingJoffrey = new KingJoffrey(); var kingsHand = new KingsHand(); kingsHand.registerObserver(kingJoffrey, Event.TRAITOR_DETECTED); kingsHand.registerObserver(kingJoffrey, Event.STARK_SIGHTED); kingsHand.registerObserver(kingJoffrey, Event.WARSHIPS_APPROACHING); kingsHand.registerObserver(kingJoffrey, Event.WHITE_WALKERS_SIGHTED); var varys = new LordVarys(); varys.registerObserver(kingsHand, Event.TRAITOR_DETECTED); varys.registerObserver(kingsHand, Event.WHITE_WALKERS_SIGHTED); var scout = new Scout(); scout.registerObserver(kingsHand, Event.WARSHIPS_APPROACHING); scout.registerObserver(varys, Event.WHITE_WALKERS_SIGHTED); var baelish = new LordBaelish(kingsHand, Event.STARK_SIGHTED); var emitters = List.of( kingsHand, baelish, varys, scout ); Arrays.stream(Weekday.values()) .<Consumer<? super EventEmitter>>map(day -> emitter -> emitter.timePasses(day)) .forEachOrdered(emitters::forEach);
56
369
425
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java
EventEmitter
registerObserver
class EventEmitter { private final Map<Event, List<EventObserver>> observerLists; public EventEmitter() { observerLists = new HashMap<>(); } public EventEmitter(EventObserver obs, Event e) { this(); registerObserver(obs, e); } /** * Registers observer for specific event in the related list. * * @param obs the observer that observers this emitter * @param e the specific event for that observation occurs * */ public final void registerObserver(EventObserver obs, Event e) {<FILL_FUNCTION_BODY>} protected void notifyObservers(Event e) { if (observerLists.containsKey(e)) { observerLists .get(e) .forEach(observer -> observer.onEvent(e)); } } public abstract void timePasses(Weekday day); }
if (!observerLists.containsKey(e)) { observerLists.put(e, new LinkedList<>()); } if (!observerLists.get(e).contains(obs)) { observerLists.get(e).add(obs); }
239
71
310
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java
Scout
timePasses
class Scout extends EventEmitter { public Scout() { } public Scout(EventObserver obs, Event e) { super(obs, e); } @Override public void timePasses(Weekday day) {<FILL_FUNCTION_BODY>} }
if (day == Weekday.TUESDAY) { notifyObservers(Event.WARSHIPS_APPROACHING); } if (day == Weekday.WEDNESDAY) { notifyObservers(Event.WHITE_WALKERS_SIGHTED); }
79
79
158
<methods>public void <init>() ,public void <init>(com.iluwatar.event.aggregator.EventObserver, com.iluwatar.event.aggregator.Event) ,public final void registerObserver(com.iluwatar.event.aggregator.EventObserver, com.iluwatar.event.aggregator.Event) ,public abstract void timePasses(com.iluwatar.event.aggregator.Weekday) <variables>private final non-sealed Map<com.iluwatar.event.aggregator.Event,List<com.iluwatar.event.aggregator.EventObserver>> observerLists
iluwatar_java-design-patterns
java-design-patterns/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java
App
quickRun
class App { public static final String PROP_FILE_NAME = "config.properties"; boolean interactiveMode = false; /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var app = new App(); app.setUp(); app.run(); } /** * App can run in interactive mode or not. Interactive mode == Allow user interaction with command * line. Non-interactive is a quick sequential run through the available {@link EventManager} * operations. */ public void setUp() { var prop = new Properties(); var inputStream = App.class.getClassLoader().getResourceAsStream(PROP_FILE_NAME); if (inputStream != null) { try { prop.load(inputStream); } catch (IOException e) { LOGGER.error("{} was not found. Defaulting to non-interactive mode.", PROP_FILE_NAME, e); } var property = prop.getProperty("INTERACTIVE_MODE"); if (property.equalsIgnoreCase("YES")) { interactiveMode = true; } } } /** * Run program in either interactive mode or not. */ public void run() { if (interactiveMode) { runInteractiveMode(); } else { quickRun(); } } /** * Run program in non-interactive mode. */ public void quickRun() {<FILL_FUNCTION_BODY>} /** * Run program in interactive mode. */ public void runInteractiveMode() { var eventManager = new EventManager(); var s = new Scanner(System.in); var option = -1; while (option != 4) { LOGGER.info("Hello. Would you like to boil some eggs?"); LOGGER.info(""" (1) BOIL AN EGG (2) STOP BOILING THIS EGG (3) HOW ARE MY EGGS? (4) EXIT """); LOGGER.info("Choose [1,2,3,4]: "); option = s.nextInt(); if (option == 1) { processOption1(eventManager, s); } else if (option == 2) { processOption2(eventManager, s); } else if (option == 3) { processOption3(eventManager, s); } else if (option == 4) { eventManager.shutdown(); } } s.close(); } private void processOption3(EventManager eventManager, Scanner s) { s.nextLine(); LOGGER.info("Just one egg (O) OR all of them (A) ?: "); var eggChoice = s.nextLine(); if (eggChoice.equalsIgnoreCase("O")) { LOGGER.info("Which egg?: "); int eventId = s.nextInt(); try { eventManager.status(eventId); } catch (EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } } else if (eggChoice.equalsIgnoreCase("A")) { eventManager.statusOfAllEvents(); } } private void processOption2(EventManager eventManager, Scanner s) { LOGGER.info("Which egg?: "); var eventId = s.nextInt(); try { eventManager.cancel(eventId); LOGGER.info("Egg [{}] is removed from boiler.", eventId); } catch (EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } } private void processOption1(EventManager eventManager, Scanner s) { s.nextLine(); LOGGER.info("Boil multiple eggs at once (A) or boil them one-by-one (S)?: "); var eventType = s.nextLine(); LOGGER.info("How long should this egg be boiled for (in seconds)?: "); var eventTime = s.nextInt(); if (eventType.equalsIgnoreCase("A")) { try { var eventId = eventManager.createAsync(eventTime); eventManager.start(eventId); LOGGER.info("Egg [{}] is being boiled.", eventId); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } } else if (eventType.equalsIgnoreCase("S")) { try { var eventId = eventManager.create(eventTime); eventManager.start(eventId); LOGGER.info("Egg [{}] is being boiled.", eventId); } catch (MaxNumOfEventsAllowedException | InvalidOperationException | LongRunningEventException | EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } } else { LOGGER.info("Unknown event type."); } } }
var eventManager = new EventManager(); try { // Create an Asynchronous event. var asyncEventId = eventManager.createAsync(60); LOGGER.info("Async Event [{}] has been created.", asyncEventId); eventManager.start(asyncEventId); LOGGER.info("Async Event [{}] has been started.", asyncEventId); // Create a Synchronous event. var syncEventId = eventManager.create(60); LOGGER.info("Sync Event [{}] has been created.", syncEventId); eventManager.start(syncEventId); LOGGER.info("Sync Event [{}] has been started.", syncEventId); eventManager.status(asyncEventId); eventManager.status(syncEventId); eventManager.cancel(asyncEventId); LOGGER.info("Async Event [{}] has been stopped.", asyncEventId); eventManager.cancel(syncEventId); LOGGER.info("Sync Event [{}] has been stopped.", syncEventId); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException | InvalidOperationException e) { LOGGER.error(e.getMessage()); }
1,292
303
1,595
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java
AsyncEvent
status
class AsyncEvent implements Event, Runnable { private final int eventId; private final int eventTime; @Getter private final boolean synchronous; private Thread thread; private boolean isComplete = false; private ThreadCompleteListener eventListener; @Override public void start() { thread = new Thread(this); thread.start(); } @Override public void stop() { if (null == thread) { return; } thread.interrupt(); } @Override public void status() {<FILL_FUNCTION_BODY>} @Override public void run() { var currentTime = System.currentTimeMillis(); var endTime = currentTime + (eventTime * 1000); while (System.currentTimeMillis() < endTime) { try { Thread.sleep(1000); // Sleep for 1 second. } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } isComplete = true; completed(); } public final void addListener(final ThreadCompleteListener listener) { this.eventListener = listener; } public final void removeListener() { this.eventListener = null; } private void completed() { if (eventListener != null) { eventListener.completedEventHandler(eventId); } } }
if (!isComplete) { LOGGER.info("[{}] is not done.", eventId); } else { LOGGER.info("[{}] is done.", eventId); }
376
52
428
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java
EventManager
generateId
class EventManager implements ThreadCompleteListener { public static final int MAX_RUNNING_EVENTS = 1000; // Just don't wanna have too many running events. :) public static final int MIN_ID = 1; public static final int MAX_ID = MAX_RUNNING_EVENTS; public static final int MAX_EVENT_TIME = 1800; // in seconds / 30 minutes. private int currentlyRunningSyncEvent = -1; private final SecureRandom rand; private final Map<Integer, AsyncEvent> eventPool; private static final String DOES_NOT_EXIST = " does not exist."; /** * EventManager constructor. */ public EventManager() { rand = new SecureRandom(); eventPool = new ConcurrentHashMap<>(MAX_RUNNING_EVENTS); } /** * Create a Synchronous event. * * @param eventTime Time an event should run for. * @return eventId * @throws MaxNumOfEventsAllowedException When too many events are running at a time. * @throws InvalidOperationException No new synchronous events can be created when one is * already running. * @throws LongRunningEventException Long running events are not allowed in the app. */ public int create(int eventTime) throws MaxNumOfEventsAllowedException, InvalidOperationException, LongRunningEventException { if (currentlyRunningSyncEvent != -1) { throw new InvalidOperationException("Event [" + currentlyRunningSyncEvent + "] is still" + " running. Please wait until it finishes and try again."); } var eventId = createEvent(eventTime, true); currentlyRunningSyncEvent = eventId; return eventId; } /** * Create an Asynchronous event. * * @param eventTime Time an event should run for. * @return eventId * @throws MaxNumOfEventsAllowedException When too many events are running at a time. * @throws LongRunningEventException Long running events are not allowed in the app. */ public int createAsync(int eventTime) throws MaxNumOfEventsAllowedException, LongRunningEventException { return createEvent(eventTime, false); } private int createEvent(int eventTime, boolean isSynchronous) throws MaxNumOfEventsAllowedException, LongRunningEventException { if (eventPool.size() == MAX_RUNNING_EVENTS) { throw new MaxNumOfEventsAllowedException("Too many events are running at the moment." + " Please try again later."); } if (eventTime >= MAX_EVENT_TIME) { throw new LongRunningEventException( "Maximum event time allowed is " + MAX_EVENT_TIME + " seconds. Please try again."); } var newEventId = generateId(); var newEvent = new AsyncEvent(newEventId, eventTime, isSynchronous); newEvent.addListener(this); eventPool.put(newEventId, newEvent); return newEventId; } /** * Starts event. * * @param eventId The event that needs to be started. * @throws EventDoesNotExistException If event does not exist in our eventPool. */ public void start(int eventId) throws EventDoesNotExistException { if (!eventPool.containsKey(eventId)) { throw new EventDoesNotExistException(eventId + DOES_NOT_EXIST); } eventPool.get(eventId).start(); } /** * Stops event. * * @param eventId The event that needs to be stopped. * @throws EventDoesNotExistException If event does not exist in our eventPool. */ public void cancel(int eventId) throws EventDoesNotExistException { if (!eventPool.containsKey(eventId)) { throw new EventDoesNotExistException(eventId + DOES_NOT_EXIST); } if (eventId == currentlyRunningSyncEvent) { currentlyRunningSyncEvent = -1; } eventPool.get(eventId).stop(); eventPool.remove(eventId); } /** * Get status of a running event. * * @param eventId The event to inquire status of. * @throws EventDoesNotExistException If event does not exist in our eventPool. */ public void status(int eventId) throws EventDoesNotExistException { if (!eventPool.containsKey(eventId)) { throw new EventDoesNotExistException(eventId + DOES_NOT_EXIST); } eventPool.get(eventId).status(); } /** * Gets status of all running events. */ @SuppressWarnings("rawtypes") public void statusOfAllEvents() { eventPool.entrySet().forEach(entry -> ((AsyncEvent) ((Map.Entry) entry).getValue()).status()); } /** * Stop all running events. */ @SuppressWarnings("rawtypes") public void shutdown() { eventPool.entrySet().forEach(entry -> ((AsyncEvent) ((Map.Entry) entry).getValue()).stop()); } /** * Returns a pseudo-random number between min and max, inclusive. The difference between min and * max can be at most * <code>Integer.MAX_VALUE - 1</code>. */ private int generateId() {<FILL_FUNCTION_BODY>} /** * Callback from an {@link AsyncEvent} (once it is complete). The Event is then removed from the pool. */ @Override public void completedEventHandler(int eventId) { eventPool.get(eventId).status(); if (eventPool.get(eventId).isSynchronous()) { currentlyRunningSyncEvent = -1; } eventPool.remove(eventId); } /** * Getter method for event pool. */ public Map<Integer, AsyncEvent> getEventPool() { return eventPool; } /** * Get number of currently running Synchronous events. */ public int numOfCurrentlyRunningSyncEvent() { return currentlyRunningSyncEvent; } }
// nextInt is normally exclusive of the top value, // so add 1 to make it inclusive var randomNum = rand.nextInt((MAX_ID - MIN_ID) + 1) + MIN_ID; while (eventPool.containsKey(randomNum)) { randomNum = rand.nextInt((MAX_ID - MIN_ID) + 1) + MIN_ID; } return randomNum;
1,597
106
1,703
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java
App
main
class App { /** * Once the {@link EventDispatcher} is initialised, handlers related to specific events have to be * made known to the dispatcher by registering them. In this case the {@link UserCreatedEvent} is * bound to the UserCreatedEventHandler, whilst the {@link UserUpdatedEvent} is bound to the * {@link UserUpdatedEventHandler}. The dispatcher can now be called to dispatch specific events. * When a user is saved, the {@link UserCreatedEvent} can be dispatched. On the other hand, when a * user is updated, {@link UserUpdatedEvent} can be dispatched. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
var dispatcher = new EventDispatcher(); dispatcher.registerHandler(UserCreatedEvent.class, new UserCreatedEventHandler()); dispatcher.registerHandler(UserUpdatedEvent.class, new UserUpdatedEventHandler()); var user = new User("iluwatar"); dispatcher.dispatch(new UserCreatedEvent(user)); dispatcher.dispatch(new UserUpdatedEvent(user));
180
97
277
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java
EventDispatcher
dispatch
class EventDispatcher { private final Map<Class<? extends Event>, Handler<? extends Event>> handlers; public EventDispatcher() { handlers = new HashMap<>(); } /** * Links an {@link Event} to a specific {@link Handler}. * * @param eventType The {@link Event} to be registered * @param handler The {@link Handler} that will be handling the {@link Event} */ public <E extends Event> void registerHandler( Class<E> eventType, Handler<E> handler ) { handlers.put(eventType, handler); } /** * Dispatches an {@link Event} depending on its type. * * @param event The {@link Event} to be dispatched */ @SuppressWarnings("unchecked") public <E extends Event> void dispatch(E event) {<FILL_FUNCTION_BODY>} }
var handler = (Handler<E>) handlers.get(event.getClass()); if (handler != null) { handler.onEvent(event); }
249
46
295
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/event-queue/src/main/java/com/iluwatar/event/queue/App.java
App
main
class App { /** * Program entry point. * * @param args command line args * @throws IOException when there is a problem with the audio file loading * @throws UnsupportedAudioFileException when the loaded audio file is unsupported */ public static void main(String[] args) throws UnsupportedAudioFileException, IOException, InterruptedException {<FILL_FUNCTION_BODY>} }
var audio = Audio.getInstance(); audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f); audio.playSound(audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f); LOGGER.info("Press Enter key to stop the program..."); try (var br = new BufferedReader(new InputStreamReader(System.in))) { br.read(); } audio.stopService();
105
136
241
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java
Audio
update
class Audio { private static final Audio INSTANCE = new Audio(); private static final int MAX_PENDING = 16; private int headIndex; private int tailIndex; private volatile Thread updateThread = null; private final PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING]; // Visible only for testing purposes Audio() { } public static Audio getInstance() { return INSTANCE; } /** * This method stops the Update Method's thread and waits till service stops. */ public synchronized void stopService() throws InterruptedException { if (updateThread != null) { updateThread.interrupt(); } updateThread.join(); updateThread = null; } /** * This method check the Update Method's thread is started. * * @return boolean */ public synchronized boolean isServiceRunning() { return updateThread != null && updateThread.isAlive(); } /** * Starts the thread for the Update Method pattern if it was not started previously. Also when the * thread is is ready initializes the indexes of the queue */ public void init() { if (updateThread == null) { updateThread = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { update(); } }); } startThread(); } /** * This is a synchronized thread starter. */ private synchronized void startThread() { if (!updateThread.isAlive()) { updateThread.start(); headIndex = 0; tailIndex = 0; } } /** * This method adds a new audio into the queue. * * @param stream is the AudioInputStream for the method * @param volume is the level of the audio's volume */ public void playSound(AudioInputStream stream, float volume) { init(); // Walk the pending requests. for (var i = headIndex; i != tailIndex; i = (i + 1) % MAX_PENDING) { var playMessage = getPendingAudio()[i]; if (playMessage.getStream() == stream) { // Use the larger of the two volumes. playMessage.setVolume(Math.max(volume, playMessage.getVolume())); // Don't need to enqueue. return; } } getPendingAudio()[tailIndex] = new PlayMessage(stream, volume); tailIndex = (tailIndex + 1) % MAX_PENDING; } /** * This method uses the Update Method pattern. It takes the audio from the queue and plays it */ private void update() {<FILL_FUNCTION_BODY>} /** * Returns the AudioInputStream of a file. * * @param filePath is the path of the audio file * @return AudioInputStream * @throws UnsupportedAudioFileException when the audio file is not supported * @throws IOException when the file is not readable */ public AudioInputStream getAudioStream(String filePath) throws UnsupportedAudioFileException, IOException { return AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile()); } /** * Returns with the message array of the queue. * * @return PlayMessage[] */ public PlayMessage[] getPendingAudio() { return pendingAudio; } }
// If there are no pending requests, do nothing. if (headIndex == tailIndex) { return; } try { var audioStream = getPendingAudio()[headIndex].getStream(); headIndex++; var clip = AudioSystem.getClip(); clip.open(audioStream); clip.start(); } catch (LineUnavailableException e) { LOGGER.trace("Error occurred while loading the audio: The line is unavailable", e); } catch (IOException e) { LOGGER.trace("Input/Output error while loading the audio", e); } catch (IllegalArgumentException e) { LOGGER.trace("The system doesn't support the sound: " + e.getMessage(), e); }
887
188
1,075
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java
App
main
class App { /** * The constant ACCOUNT OF DAENERYS. */ public static final int ACCOUNT_OF_DAENERYS = 1; /** * The constant ACCOUNT OF JON. */ public static final int ACCOUNT_OF_JON = 2; /** * The entry point of application. * * @param args the input arguments */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
var eventProcessor = new DomainEventProcessor(new JsonFileJournal()); LOGGER.info("Running the system first time............"); eventProcessor.reset(); LOGGER.info("Creating the accounts............"); eventProcessor.process(new AccountCreateEvent( 0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen")); eventProcessor.process(new AccountCreateEvent( 1, new Date().getTime(), ACCOUNT_OF_JON, "Jon Snow")); LOGGER.info("Do some money operations............"); eventProcessor.process(new MoneyDepositEvent( 2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000"))); eventProcessor.process(new MoneyDepositEvent( 3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100"))); eventProcessor.process(new MoneyTransferEvent( 4, new Date().getTime(), new BigDecimal("10000"), ACCOUNT_OF_DAENERYS, ACCOUNT_OF_JON)); LOGGER.info("...............State:............"); LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS).toString()); LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_JON).toString()); LOGGER.info("At that point system had a shut down, state in memory is cleared............"); AccountAggregate.resetState(); LOGGER.info("Recover the system by the events in journal file............"); eventProcessor = new DomainEventProcessor(new JsonFileJournal()); eventProcessor.recover(); LOGGER.info("...............Recovered State:............"); LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS).toString()); LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_JON).toString());
132
514
646
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java
Account
toString
class Account { private final int accountNo; private final String owner; private BigDecimal money = BigDecimal.ZERO; private static final String MSG = "Some external api for only realtime execution could be called here."; /** * Copy account. * * @return the account */ public Account copy() { var account = new Account(accountNo, owner); account.setMoney(money); return account; } @Override public String toString() {<FILL_FUNCTION_BODY>} private void depositMoney(BigDecimal money) { this.money = this.money.add(money); } private void withdrawMoney(BigDecimal money) { this.money = this.money.subtract(money); } private void handleDeposit(BigDecimal money, boolean realTime) { depositMoney(money); AccountAggregate.putAccount(this); if (realTime) { LOGGER.info(MSG); } } private void handleWithdrawal(BigDecimal money, boolean realTime) { if (this.money.compareTo(money) < 0) { throw new RuntimeException("Insufficient Account Balance"); } withdrawMoney(money); AccountAggregate.putAccount(this); if (realTime) { LOGGER.info(MSG); } } /** * Handles the MoneyDepositEvent. * * @param moneyDepositEvent the money deposit event */ public void handleEvent(MoneyDepositEvent moneyDepositEvent) { handleDeposit(moneyDepositEvent.getMoney(), moneyDepositEvent.isRealTime()); } /** * Handles the AccountCreateEvent. * * @param accountCreateEvent the account created event */ public void handleEvent(AccountCreateEvent accountCreateEvent) { AccountAggregate.putAccount(this); if (accountCreateEvent.isRealTime()) { LOGGER.info(MSG); } } /** * Handles transfer from account event. * * @param moneyTransferEvent the money transfer event */ public void handleTransferFromEvent(MoneyTransferEvent moneyTransferEvent) { handleWithdrawal(moneyTransferEvent.getMoney(), moneyTransferEvent.isRealTime()); } /** * Handles transfer to account event. * * @param moneyTransferEvent the money transfer event */ public void handleTransferToEvent(MoneyTransferEvent moneyTransferEvent) { handleDeposit(moneyTransferEvent.getMoney(), moneyTransferEvent.isRealTime()); } }
return "Account{" + "accountNo=" + accountNo + ", owner='" + owner + '\'' + ", money=" + money + '}';
717
47
764
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java
AccountCreateEvent
process
class AccountCreateEvent extends DomainEvent { private final int accountNo; private final String owner; /** * Instantiates a new Account created event. * * @param sequenceId the sequence id * @param createdTime the created time * @param accountNo the account no * @param owner the owner */ @JsonCreator public AccountCreateEvent(@JsonProperty("sequenceId") long sequenceId, @JsonProperty("createdTime") long createdTime, @JsonProperty("accountNo") int accountNo, @JsonProperty("owner") String owner) { super(sequenceId, createdTime, "AccountCreateEvent"); this.accountNo = accountNo; this.owner = owner; } @Override public void process() {<FILL_FUNCTION_BODY>} }
var account = AccountAggregate.getAccount(accountNo); if (account != null) { throw new RuntimeException("Account already exists"); } account = new Account(accountNo, owner); account.handleEvent(this);
210
63
273
<methods>public non-sealed void <init>() ,public abstract void process() <variables>private final non-sealed long createdTime,private final non-sealed java.lang.String eventClassName,private boolean realTime,private final non-sealed long sequenceId
iluwatar_java-design-patterns
java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java
MoneyDepositEvent
process
class MoneyDepositEvent extends DomainEvent { private final BigDecimal money; private final int accountNo; /** * Instantiates a new Money deposit event. * * @param sequenceId the sequence id * @param createdTime the created time * @param accountNo the account no * @param money the money */ @JsonCreator public MoneyDepositEvent(@JsonProperty("sequenceId") long sequenceId, @JsonProperty("createdTime") long createdTime, @JsonProperty("accountNo") int accountNo, @JsonProperty("money") BigDecimal money) { super(sequenceId, createdTime, "MoneyDepositEvent"); this.money = money; this.accountNo = accountNo; } @Override public void process() {<FILL_FUNCTION_BODY>} }
var account = Optional.ofNullable(AccountAggregate.getAccount(accountNo)) .orElseThrow(() -> new RuntimeException("Account not found")); account.handleEvent(this);
221
50
271
<methods>public non-sealed void <init>() ,public abstract void process() <variables>private final non-sealed long createdTime,private final non-sealed java.lang.String eventClassName,private boolean realTime,private final non-sealed long sequenceId
iluwatar_java-design-patterns
java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java
MoneyTransferEvent
process
class MoneyTransferEvent extends DomainEvent { private final BigDecimal money; private final int accountNoFrom; private final int accountNoTo; /** * Instantiates a new Money transfer event. * * @param sequenceId the sequence id * @param createdTime the created time * @param money the money * @param accountNoFrom the account no from * @param accountNoTo the account no to */ @JsonCreator public MoneyTransferEvent(@JsonProperty("sequenceId") long sequenceId, @JsonProperty("createdTime") long createdTime, @JsonProperty("money") BigDecimal money, @JsonProperty("accountNoFrom") int accountNoFrom, @JsonProperty("accountNoTo") int accountNoTo) { super(sequenceId, createdTime, "MoneyTransferEvent"); this.money = money; this.accountNoFrom = accountNoFrom; this.accountNoTo = accountNoTo; } @Override public void process() {<FILL_FUNCTION_BODY>} }
var accountFrom = Optional.ofNullable(AccountAggregate.getAccount(accountNoFrom)) .orElseThrow(() -> new RuntimeException("Account not found " + accountNoFrom)); var accountTo = Optional.ofNullable(AccountAggregate.getAccount(accountNoTo)) .orElseThrow(() -> new RuntimeException("Account not found " + accountNoTo)); accountFrom.handleTransferFromEvent(this); accountTo.handleTransferToEvent(this);
274
119
393
<methods>public non-sealed void <init>() ,public abstract void process() <variables>private final non-sealed long createdTime,private final non-sealed java.lang.String eventClassName,private boolean realTime,private final non-sealed long sequenceId
iluwatar_java-design-patterns
java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java
DomainEventProcessor
recover
class DomainEventProcessor { private final EventJournal eventJournal; public DomainEventProcessor(EventJournal eventJournal) { this.eventJournal = eventJournal; } /** * Process. * * @param domainEvent the domain event */ public void process(DomainEvent domainEvent) { domainEvent.process(); eventJournal.write(domainEvent); } /** * Reset. */ public void reset() { eventJournal.reset(); } /** * Recover. */ public void recover() {<FILL_FUNCTION_BODY>} }
DomainEvent domainEvent; while ((domainEvent = eventJournal.readNext()) != null) { domainEvent.process(); }
174
40
214
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java
JsonFileJournal
write
class JsonFileJournal extends EventJournal { private final List<String> events = new ArrayList<>(); private int index = 0; /** * Instantiates a new Json file journal. */ public JsonFileJournal() { file = new File("Journal.json"); if (file.exists()) { try (var input = new BufferedReader( new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { String line; while ((line = input.readLine()) != null) { events.add(line); } } catch (IOException e) { throw new RuntimeException(e); } } else { reset(); } } /** * Write. * * @param domainEvent the domain event */ @Override public void write(DomainEvent domainEvent) {<FILL_FUNCTION_BODY>} /** * Read the next domain event. * * @return the domain event */ public DomainEvent readNext() { if (index >= events.size()) { return null; } var event = events.get(index); index++; var mapper = new ObjectMapper(); DomainEvent domainEvent; try { var jsonElement = mapper.readTree(event); var eventClassName = jsonElement.get("eventClassName").asText(); domainEvent = switch (eventClassName) { case "AccountCreateEvent" -> mapper.treeToValue(jsonElement, AccountCreateEvent.class); case "MoneyDepositEvent" -> mapper.treeToValue(jsonElement, MoneyDepositEvent.class); case "MoneyTransferEvent" -> mapper.treeToValue(jsonElement, MoneyTransferEvent.class); default -> throw new RuntimeException("Journal Event not recognized"); }; } catch (JsonProcessingException jsonProcessingException) { throw new RuntimeException("Failed to convert JSON"); } domainEvent.setRealTime(false); return domainEvent; } }
var mapper = new ObjectMapper(); try (var output = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8))) { var eventString = mapper.writeValueAsString(domainEvent); output.write(eventString + "\r\n"); } catch (IOException e) { throw new RuntimeException(e); }
538
101
639
<methods>public non-sealed void <init>() <variables>java.io.File file
iluwatar_java-design-patterns
java-design-patterns/execute-around/src/main/java/com/iluwatar/execute/around/App.java
App
main
class App { /** * Program entry point. */ public static void main(String[] args) throws IOException {<FILL_FUNCTION_BODY>} }
// create the file writer and execute the custom action FileWriterAction writeHello = writer -> { writer.write("Gandalf was here"); }; new SimpleFileWriter("testfile.txt", writeHello); // print the file contents try (var scanner = new Scanner(new File("testfile.txt"))) { while (scanner.hasNextLine()) { LOGGER.info(scanner.nextLine()); } }
46
119
165
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/extension-objects/src/main/java/App.java
App
checkExtensionsForUnit
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { //Create 3 different units var soldierUnit = new SoldierUnit("SoldierUnit1"); var sergeantUnit = new SergeantUnit("SergeantUnit1"); var commanderUnit = new CommanderUnit("CommanderUnit1"); //check for each unit to have an extension checkExtensionsForUnit(soldierUnit); checkExtensionsForUnit(sergeantUnit); checkExtensionsForUnit(commanderUnit); } private static void checkExtensionsForUnit(Unit unit) {<FILL_FUNCTION_BODY>} }
final var logger = LoggerFactory.getLogger(App.class); var name = unit.getName(); Function<String, Runnable> func = e -> () -> logger.info("{} without {}", name, e); var extension = "SoldierExtension"; Optional.ofNullable(unit.getUnitExtension(extension)) .map(e -> (SoldierExtension) e) .ifPresentOrElse(SoldierExtension::soldierReady, func.apply(extension)); extension = "SergeantExtension"; Optional.ofNullable(unit.getUnitExtension(extension)) .map(e -> (SergeantExtension) e) .ifPresentOrElse(SergeantExtension::sergeantReady, func.apply(extension)); extension = "CommanderExtension"; Optional.ofNullable(unit.getUnitExtension(extension)) .map(e -> (CommanderExtension) e) .ifPresentOrElse(CommanderExtension::commanderReady, func.apply(extension));
184
254
438
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/extension-objects/src/main/java/units/CommanderUnit.java
CommanderUnit
getUnitExtension
class CommanderUnit extends Unit { public CommanderUnit(String name) { super(name); } @Override public UnitExtension getUnitExtension(String extensionName) {<FILL_FUNCTION_BODY>} }
if (extensionName.equals("CommanderExtension")) { return Optional.ofNullable(unitExtension).orElseGet(() -> new Commander(this)); } return super.getUnitExtension(extensionName);
62
58
120
<methods>public void <init>(java.lang.String) ,public abstractextensions.UnitExtension getUnitExtension(java.lang.String) <variables>private java.lang.String name,protected abstractextensions.UnitExtension unitExtension
iluwatar_java-design-patterns
java-design-patterns/extension-objects/src/main/java/units/SergeantUnit.java
SergeantUnit
getUnitExtension
class SergeantUnit extends Unit { public SergeantUnit(String name) { super(name); } @Override public UnitExtension getUnitExtension(String extensionName) {<FILL_FUNCTION_BODY>} }
if (extensionName.equals("SergeantExtension")) { return Optional.ofNullable(unitExtension).orElseGet(() -> new Sergeant(this)); } return super.getUnitExtension(extensionName);
62
58
120
<methods>public void <init>(java.lang.String) ,public abstractextensions.UnitExtension getUnitExtension(java.lang.String) <variables>private java.lang.String name,protected abstractextensions.UnitExtension unitExtension
iluwatar_java-design-patterns
java-design-patterns/extension-objects/src/main/java/units/SoldierUnit.java
SoldierUnit
getUnitExtension
class SoldierUnit extends Unit { public SoldierUnit(String name) { super(name); } @Override public UnitExtension getUnitExtension(String extensionName) {<FILL_FUNCTION_BODY>} }
if (extensionName.equals("SoldierExtension")) { return Optional.ofNullable(unitExtension).orElseGet(() -> new Soldier(this)); } return super.getUnitExtension(extensionName);
62
59
121
<methods>public void <init>(java.lang.String) ,public abstractextensions.UnitExtension getUnitExtension(java.lang.String) <variables>private java.lang.String name,protected abstractextensions.UnitExtension unitExtension
iluwatar_java-design-patterns
java-design-patterns/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java
DwarvenCartOperator
work
class DwarvenCartOperator extends DwarvenMineWorker { @Override public void work() {<FILL_FUNCTION_BODY>} @Override public String name() { return "Dwarf cart operator"; } }
LOGGER.info("{} moves gold chunks out of the mine.", name());
76
24
100
<methods>public non-sealed void <init>() ,public transient void action(com.iluwatar.facade.DwarvenMineWorker.Action[]) ,public void goHome() ,public void goToMine() ,public void goToSleep() ,public abstract java.lang.String name() ,public void wakeUp() ,public abstract void work() <variables>
iluwatar_java-design-patterns
java-design-patterns/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java
DwarvenMineWorker
action
class DwarvenMineWorker { public void goToSleep() { LOGGER.info("{} goes to sleep.", name()); } public void wakeUp() { LOGGER.info("{} wakes up.", name()); } public void goHome() { LOGGER.info("{} goes home.", name()); } public void goToMine() { LOGGER.info("{} goes to the mine.", name()); } private void action(Action action) {<FILL_FUNCTION_BODY>} /** * Perform actions. */ public void action(Action... actions) { Arrays.stream(actions).forEach(this::action); } public abstract void work(); public abstract String name(); enum Action { GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK } }
switch (action) { case GO_TO_SLEEP -> goToSleep(); case WAKE_UP -> wakeUp(); case GO_HOME -> goHome(); case GO_TO_MINE -> goToMine(); case WORK -> work(); default -> LOGGER.info("Undefined action"); }
273
102
375
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/factory-kit/src/main/java/com/iluwatar/factorykit/App.java
App
main
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
var factory = WeaponFactory.factory(builder -> { builder.add(WeaponType.SWORD, Sword::new); builder.add(WeaponType.AXE, Axe::new); builder.add(WeaponType.SPEAR, Spear::new); builder.add(WeaponType.BOW, Bow::new); }); var list = new ArrayList<Weapon>(); list.add(factory.create(WeaponType.AXE)); list.add(factory.create(WeaponType.SPEAR)); list.add(factory.create(WeaponType.SWORD)); list.add(factory.create(WeaponType.BOW)); list.forEach(weapon -> LOGGER.info("{}", weapon.toString()));
56
206
262
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/factory-method/src/main/java/com/iluwatar/factory/method/App.java
App
main
class App { private static final String MANUFACTURED = "{} manufactured {}"; /** * Program entry point. * @param args command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
Blacksmith blacksmith = new OrcBlacksmith(); Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); LOGGER.info(MANUFACTURED, blacksmith, weapon); weapon = blacksmith.manufactureWeapon(WeaponType.AXE); LOGGER.info(MANUFACTURED, blacksmith, weapon); blacksmith = new ElfBlacksmith(); weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); LOGGER.info(MANUFACTURED, blacksmith, weapon); weapon = blacksmith.manufactureWeapon(WeaponType.AXE); LOGGER.info(MANUFACTURED, blacksmith, weapon);
72
198
270
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/factory/src/main/java/com/iluwatar/factory/App.java
App
main
class App { /** * Program main entry point. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
LOGGER.info("The alchemist begins his work."); var coin1 = CoinFactory.getCoin(CoinType.COPPER); var coin2 = CoinFactory.getCoin(CoinType.GOLD); LOGGER.info(coin1.getDescription()); LOGGER.info(coin2.getDescription());
45
87
132
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/App.java
App
main
class App { /** * Entry point. * * <p>Implementation provided has a list of numbers that has to be squared and added. The list can * be chunked in any way and the "activity function" {@link * SquareNumberRequest#delayedSquaring(Consumer)} i.e. squaring the number ca be done * concurrently. The "fan in" part is handled by the {@link Consumer} that takes in the result * from each instance of activity and aggregates it whenever that particular activity function * gets over. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
final List<Long> numbers = Arrays.asList(1L, 3L, 4L, 7L, 8L); LOGGER.info("Numbers to be squared and get sum --> {}", numbers); final List<SquareNumberRequest> requests = numbers.stream().map(SquareNumberRequest::new).toList(); var consumer = new Consumer(0L); // Pass the request and the consumer to fanOutFanIn or sometimes referred as Orchestrator // function final Long sumOfSquaredNumbers = FanOutFanIn.fanOutFanIn(requests, consumer); LOGGER.info("Sum of all squared numbers --> {}", sumOfSquaredNumbers);
165
187
352
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/FanOutFanIn.java
FanOutFanIn
fanOutFanIn
class FanOutFanIn { /** * the main fanOutFanIn function or orchestrator function. * @param requests List of numbers that need to be squared and summed up * @param consumer Takes in the squared number from {@link SquareNumberRequest} and sums it up * @return Aggregated sum of all squared numbers. */ public static Long fanOutFanIn( final List<SquareNumberRequest> requests, final Consumer consumer) {<FILL_FUNCTION_BODY>} }
ExecutorService service = Executors.newFixedThreadPool(requests.size()); // fanning out List<CompletableFuture<Void>> futures = requests.stream() .map( request -> CompletableFuture.runAsync(() -> request.delayedSquaring(consumer), service)) .toList(); CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); return consumer.getSumOfSquaredNumbers().get();
134
135
269
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/SquareNumberRequest.java
SquareNumberRequest
delayedSquaring
class SquareNumberRequest { private final Long number; /** * Squares the number with a little timeout to give impression of long running process that return * at different times. * @param consumer callback class that takes the result after the delay. * */ public void delayedSquaring(final Consumer consumer) {<FILL_FUNCTION_BODY>} }
var minTimeOut = 5000L; SecureRandom secureRandom = new SecureRandom(); var randomTimeOut = secureRandom.nextInt(2000); try { // this will make the thread sleep from 5-7s. Thread.sleep(minTimeOut + randomTimeOut); } catch (InterruptedException e) { LOGGER.error("Exception while sleep ", e); Thread.currentThread().interrupt(); } finally { consumer.add(number * number); }
95
136
231
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java
App
main
class App { /** * Block 1 shows the {@link PropertiesFeatureToggleVersion} being run with {@link Properties} * setting the feature toggle to enabled. * * <p>Block 2 shows the {@link PropertiesFeatureToggleVersion} being run with {@link Properties} * setting the feature toggle to disabled. Notice the difference with the printed welcome message * the username is not included. * * <p>Block 3 shows the {@link * com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion} being set up with * two users on who is on the free level, while the other is on the paid level. When the {@link * Service#getWelcomeMessage(User)} is called with the paid {@link User} note that the welcome * message contains their username, while the same service call with the free tier user is more * generic. No username is printed. * * @see User * @see UserGroup * @see Service * @see PropertiesFeatureToggleVersion * @see com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
final var properties = new Properties(); properties.put("enhancedWelcome", true); var service = new PropertiesFeatureToggleVersion(properties); final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); LOGGER.info(welcomeMessage); // --------------------------------------------- final var turnedOff = new Properties(); turnedOff.put("enhancedWelcome", false); var turnedOffService = new PropertiesFeatureToggleVersion(turnedOff); final var welcomeMessageturnedOff = turnedOffService.getWelcomeMessage(new User("Jamie No Code")); LOGGER.info(welcomeMessageturnedOff); // -------------------------------------------- var service2 = new TieredFeatureToggleVersion(); final var paidUser = new User("Jamie Coder"); final var freeUser = new User("Alan Defect"); UserGroup.addUserToPaidGroup(paidUser); UserGroup.addUserToFreeGroup(freeUser); final var welcomeMessagePaidUser = service2.getWelcomeMessage(paidUser); final var welcomeMessageFreeUser = service2.getWelcomeMessage(freeUser); LOGGER.info(welcomeMessageFreeUser); LOGGER.info(welcomeMessagePaidUser);
316
321
637
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java
PropertiesFeatureToggleVersion
getWelcomeMessage
class PropertiesFeatureToggleVersion implements Service { /** * True if the welcome message to be returned is the enhanced venison or not. For * this service it will see the value of the boolean that was set in the constructor {@link * PropertiesFeatureToggleVersion#PropertiesFeatureToggleVersion(Properties)} */ private final boolean enhanced; /** * Creates an instance of {@link PropertiesFeatureToggleVersion} using the passed {@link * Properties} to determine, the status of the feature toggle {@link * PropertiesFeatureToggleVersion#isEnhanced()}. There is also some defensive code to ensure the * {@link Properties} passed are as expected. * * @param properties {@link Properties} used to configure the service and toggle features. * @throws IllegalArgumentException when the passed {@link Properties} is not as expected * @see Properties */ public PropertiesFeatureToggleVersion(final Properties properties) { if (properties == null) { throw new IllegalArgumentException("No Properties Provided."); } else { try { enhanced = (boolean) properties.get("enhancedWelcome"); } catch (Exception e) { throw new IllegalArgumentException("Invalid Enhancement Settings Provided."); } } } /** * Generate a welcome message based on the user being passed and the status of the feature toggle. * If the enhanced version is enabled, then the message will be personalised with the name of the * passed {@link User}. However if disabled then a generic version fo the message is returned. * * @param user the {@link User} to be displayed in the message if the enhanced version is enabled * see {@link PropertiesFeatureToggleVersion#isEnhanced()}. If the enhanced version is * enabled, then the message will be personalised with the name of the passed {@link * User}. However if disabled then a generic version fo the message is returned. * @return Resulting welcome message. * @see User */ @Override public String getWelcomeMessage(final User user) {<FILL_FUNCTION_BODY>} }
if (isEnhanced()) { return "Welcome " + user + ". You're using the enhanced welcome message."; } return "Welcome to the application.";
511
48
559
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java
TieredFeatureToggleVersion
getWelcomeMessage
class TieredFeatureToggleVersion implements Service { /** * Generates a welcome message from the passed {@link User}. The resulting message depends on the * group of the {@link User}. So if the {@link User} is in the {@link UserGroup#paidGroup} then * the enhanced version of the welcome message will be returned where the username is displayed. * * @param user the {@link User} to generate the welcome message for, different messages are * displayed if the user is in the {@link UserGroup#isPaid(User)} or {@link * UserGroup#freeGroup} * @return Resulting welcome message. * @see User * @see UserGroup */ @Override public String getWelcomeMessage(User user) {<FILL_FUNCTION_BODY>} /** * Method that checks if the welcome message to be returned is the enhanced version. For this * instance as the logic is driven by the user group. This method is a little redundant. However * can be used to show that there is an enhanced version available. * * @return Boolean value {@code true} if enhanced. */ @Override public boolean isEnhanced() { return true; } }
if (UserGroup.isPaid(user)) { return "You're amazing " + user + ". Thanks for paying for this awesome software."; } return "I suppose you can use this software.";
306
56
362
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java
UserGroup
addUserToFreeGroup
class UserGroup { private static final List<User> freeGroup = new ArrayList<>(); private static final List<User> paidGroup = new ArrayList<>(); /** * Add the passed {@link User} to the free user group list. * * @param user {@link User} to be added to the free group * @throws IllegalArgumentException when user is already added to the paid group * @see User */ public static void addUserToFreeGroup(final User user) throws IllegalArgumentException {<FILL_FUNCTION_BODY>} /** * Add the passed {@link User} to the paid user group list. * * @param user {@link User} to be added to the paid group * @throws IllegalArgumentException when the user is already added to the free group * @see User */ public static void addUserToPaidGroup(final User user) throws IllegalArgumentException { if (freeGroup.contains(user)) { throw new IllegalArgumentException("User already member of free group."); } else { if (!paidGroup.contains(user)) { paidGroup.add(user); } } } /** * Method to take a {@link User} to determine if the user is in the {@link UserGroup#paidGroup}. * * @param user {@link User} to check if they are in the {@link UserGroup#paidGroup} * @return true if the {@link User} is in {@link UserGroup#paidGroup} */ public static boolean isPaid(User user) { return paidGroup.contains(user); } }
if (paidGroup.contains(user)) { throw new IllegalArgumentException("User already member of paid group."); } else { if (!freeGroup.contains(user)) { freeGroup.add(user); } }
395
61
456
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/filterer/src/main/java/com/iluwatar/filterer/App.java
App
filteringSimpleThreats
class App { public static void main(String[] args) { filteringSimpleThreats(); filteringSimpleProbableThreats(); } /** * Demonstrates how to filter {@link com.iluwatar.filterer.threat.ProbabilisticThreatAwareSystem} * based on probability property. The @{@link com.iluwatar.filterer.domain.Filterer#by(Predicate)} * method is able to use {@link com.iluwatar.filterer.threat.ProbableThreat} * as predicate argument. */ private static void filteringSimpleProbableThreats() { LOGGER.info("### Filtering ProbabilisticThreatAwareSystem by probability ###"); var trojanArcBomb = new SimpleProbableThreat("Trojan-ArcBomb", 1, ThreatType.TROJAN, 0.99); var rootkit = new SimpleProbableThreat("Rootkit-Kernel", 2, ThreatType.ROOTKIT, 0.8); List<ProbableThreat> probableThreats = List.of(trojanArcBomb, rootkit); var probabilisticThreatAwareSystem = new SimpleProbabilisticThreatAwareSystem("Sys-1", probableThreats); LOGGER.info("Filtering ProbabilisticThreatAwareSystem. Initial : " + probabilisticThreatAwareSystem); //Filtering using filterer var filteredThreatAwareSystem = probabilisticThreatAwareSystem.filtered() .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0); LOGGER.info("Filtered by probability = 0.99 : " + filteredThreatAwareSystem); } /** * Demonstrates how to filter {@link ThreatAwareSystem} based on startingOffset property * of {@link SimpleThreat}. The @{@link com.iluwatar.filterer.domain.Filterer#by(Predicate)} * method is able to use {@link Threat} as predicate argument. */ private static void filteringSimpleThreats() {<FILL_FUNCTION_BODY>} }
LOGGER.info("### Filtering ThreatAwareSystem by ThreatType ###"); var rootkit = new SimpleThreat(ThreatType.ROOTKIT, 1, "Simple-Rootkit"); var trojan = new SimpleThreat(ThreatType.TROJAN, 2, "Simple-Trojan"); List<Threat> threats = List.of(rootkit, trojan); var threatAwareSystem = new SimpleThreatAwareSystem("Sys-1", threats); LOGGER.info("Filtering ThreatAwareSystem. Initial : " + threatAwareSystem); //Filtering using Filterer var rootkitThreatAwareSystem = threatAwareSystem.filtered() .by(threat -> threat.type() == ThreatType.ROOTKIT); LOGGER.info("Filtered by threatType = ROOTKIT : " + rootkitThreatAwareSystem);
569
234
803
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbableThreat.java
SimpleProbableThreat
toString
class SimpleProbableThreat extends SimpleThreat implements ProbableThreat { private final double probability; public SimpleProbableThreat(final String name, final int id, final ThreatType threatType, final double probability) { super(threatType, id, name); this.probability = probability; } /** * {@inheritDoc} */ @Override public double probability() { return probability; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "SimpleProbableThreat{" + "probability=" + probability + "} " + super.toString();
141
36
177
<methods>public non-sealed void <init>() ,public int id() ,public java.lang.String name() ,public com.iluwatar.filterer.threat.ThreatType type() <variables>private final non-sealed int id,private final non-sealed java.lang.String name,private final non-sealed com.iluwatar.filterer.threat.ThreatType threatType
iluwatar_java-design-patterns
java-design-patterns/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java
App
main
class App { /** * Program entry point. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} private static Function<Integer, String> transformToString() { return integer -> "String[" + integer + "]"; } private static Predicate<? super Integer> negatives() { return integer -> integer < 0; } private static Predicate<? super Integer> positives() { return integer -> integer > 0; } private static <E> void prettyPrint(String prefix, Iterable<E> iterable) { prettyPrint(", ", prefix, iterable); } private static <E> void prettyPrint( String delimiter, String prefix, Iterable<E> iterable ) { var joiner = new StringJoiner(delimiter, prefix, "."); iterable.forEach(e -> joiner.add(e.toString())); LOGGER.info(joiner.toString()); } }
var integerList = List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68); prettyPrint("The initial list contains: ", integerList); var firstFiveNegatives = SimpleFluentIterable .fromCopyOf(integerList) .filter(negatives()) .first(3) .asList(); prettyPrint("The first three negative values are: ", firstFiveNegatives); var lastTwoPositives = SimpleFluentIterable .fromCopyOf(integerList) .filter(positives()) .last(2) .asList(); prettyPrint("The last two positive values are: ", lastTwoPositives); SimpleFluentIterable .fromCopyOf(integerList) .filter(number -> number % 2 == 0) .first() .ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber)); var transformedList = SimpleFluentIterable .fromCopyOf(integerList) .filter(negatives()) .map(transformToString()) .asList(); prettyPrint("A string-mapped list of negative numbers contains: ", transformedList); var lastTwoOfFirstFourStringMapped = LazyFluentIterable .from(integerList) .filter(positives()) .first(4) .last(2) .map(number -> "String[" + number + "]") .asList(); prettyPrint("The lazy list contains the last two of the first four positive numbers " + "mapped to Strings: ", lastTwoOfFirstFourStringMapped); LazyFluentIterable .from(integerList) .filter(negatives()) .first(2) .last() .ifPresent(number -> LOGGER.info("Last amongst first two negatives: {}", number));
262
527
789
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java
DecoratingIterator
next
class DecoratingIterator<E> implements Iterator<E> { protected final Iterator<E> fromIterator; private E next; /** * Creates an iterator that decorates the given iterator. */ public DecoratingIterator(Iterator<E> fromIterator) { this.fromIterator = fromIterator; } /** * Precomputes and saves the next element of the Iterable. null is considered as end of data. * * @return true if a next element is available */ @Override public final boolean hasNext() { next = computeNext(); return next != null; } /** * Returns the next element of the Iterable. * * @return the next element of the Iterable, or null if not present. */ @Override public final E next() {<FILL_FUNCTION_BODY>} /** * Computes the next object of the Iterable. Can be implemented to realize custom behaviour for an * iteration process. null is considered as end of data. * * @return the next element of the Iterable. */ public abstract E computeNext(); }
if (next == null) { return fromIterator.next(); } else { final var result = next; next = null; return result; }
297
47
344
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java
LazyFluentIterable
map
class LazyFluentIterable<E> implements FluentIterable<E> { private final Iterable<E> iterable; /** * This constructor can be used to implement anonymous subclasses of the LazyFluentIterable. */ protected LazyFluentIterable() { iterable = this; } /** * Filters the contents of Iterable using the given predicate, leaving only the ones which satisfy * the predicate. * * @param predicate the condition to test with for the filtering. If the test is negative, the * tested object is removed by the iterator. * @return a new FluentIterable object that decorates the source iterable */ @Override public FluentIterable<E> filter(Predicate<? super E> predicate) { return new LazyFluentIterable<>() { @Override public Iterator<E> iterator() { return new DecoratingIterator<>(iterable.iterator()) { @Override public E computeNext() { while (fromIterator.hasNext()) { var candidate = fromIterator.next(); if (predicate.test(candidate)) { return candidate; } } return null; } }; } }; } /** * Can be used to collect objects from the iteration. Is a terminating operation. * * @return an Optional containing the first object of this Iterable */ @Override public Optional<E> first() { var resultIterator = first(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); } /** * Can be used to collect objects from the iteration. * * @param count defines the number of objects to return * @return the same FluentIterable with a collection decimated to a maximum of 'count' first * objects. */ @Override public FluentIterable<E> first(int count) { return new LazyFluentIterable<>() { @Override public Iterator<E> iterator() { return new DecoratingIterator<>(iterable.iterator()) { int currentIndex; @Override public E computeNext() { if (currentIndex < count && fromIterator.hasNext()) { var candidate = fromIterator.next(); currentIndex++; return candidate; } return null; } }; } }; } /** * Can be used to collect objects from the iteration. Is a terminating operation. * * @return an Optional containing the last object of this Iterable */ @Override public Optional<E> last() { var resultIterator = last(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); } /** * Can be used to collect objects from the Iterable. Is a terminating operation. This operation is * memory intensive, because the contents of this Iterable are collected into a List, when the * next object is requested. * * @param count defines the number of objects to return * @return the same FluentIterable with a collection decimated to a maximum of 'count' last * objects */ @Override public FluentIterable<E> last(int count) { return new LazyFluentIterable<>() { @Override public Iterator<E> iterator() { return new DecoratingIterator<>(iterable.iterator()) { private int stopIndex; private int totalElementsCount; private List<E> list; private int currentIndex; @Override public E computeNext() { initialize(); while (currentIndex < stopIndex && fromIterator.hasNext()) { currentIndex++; fromIterator.next(); } if (currentIndex >= stopIndex && fromIterator.hasNext()) { return fromIterator.next(); } return null; } private void initialize() { if (list == null) { list = new ArrayList<>(); iterable.forEach(list::add); totalElementsCount = list.size(); stopIndex = totalElementsCount - count; } } }; } }; } /** * Transforms this FluentIterable into a new one containing objects of the type T. * * @param function a function that transforms an instance of E into an instance of T * @param <T> the target type of the transformation * @return a new FluentIterable of the new type */ @Override public <T> FluentIterable<T> map(Function<? super E, T> function) {<FILL_FUNCTION_BODY>} /** * Collects all remaining objects of this iteration into a list. * * @return a list with all remaining objects of this iteration */ @Override public List<E> asList() { return FluentIterable.copyToList(iterable); } @Override public Iterator<E> iterator() { return new DecoratingIterator<>(iterable.iterator()) { @Override public E computeNext() { return fromIterator.hasNext() ? fromIterator.next() : null; } }; } /** * Constructors FluentIterable from given iterable. * * @return a FluentIterable from a given iterable. Calls the LazyFluentIterable constructor. */ public static <E> FluentIterable<E> from(Iterable<E> iterable) { return new LazyFluentIterable<>(iterable); } }
return new LazyFluentIterable<>() { @Override public Iterator<T> iterator() { return new DecoratingIterator<>(null) { final Iterator<E> oldTypeIterator = iterable.iterator(); @Override public T computeNext() { if (oldTypeIterator.hasNext()) { E candidate = oldTypeIterator.next(); return function.apply(candidate); } else { return null; } } }; } };
1,472
133
1,605
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java
SimpleFluentIterable
first
class SimpleFluentIterable<E> implements FluentIterable<E> { private final Iterable<E> iterable; /** * Filters the contents of Iterable using the given predicate, leaving only the ones which satisfy * the predicate. * * @param predicate the condition to test with for the filtering. If the test is negative, the * tested object is removed by the iterator. * @return the same FluentIterable with a filtered collection */ @Override public final FluentIterable<E> filter(Predicate<? super E> predicate) { var iterator = iterator(); while (iterator.hasNext()) { var nextElement = iterator.next(); if (!predicate.test(nextElement)) { iterator.remove(); } } return this; } /** * Can be used to collect objects from the Iterable. Is a terminating operation. * * @return an option of the first object of the Iterable */ @Override public final Optional<E> first() { var resultIterator = first(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); } /** * Can be used to collect objects from the Iterable. Is a terminating operation. * * @param count defines the number of objects to return * @return the same FluentIterable with a collection decimated to a maximum of 'count' first * objects. */ @Override public final FluentIterable<E> first(int count) {<FILL_FUNCTION_BODY>} /** * Can be used to collect objects from the Iterable. Is a terminating operation. * * @return an option of the last object of the Iterable */ @Override public final Optional<E> last() { var list = last(1).asList(); if (list.isEmpty()) { return Optional.empty(); } return Optional.of(list.get(0)); } /** * Can be used to collect objects from the Iterable. Is a terminating operation. * * @param count defines the number of objects to return * @return the same FluentIterable with a collection decimated to a maximum of 'count' last * objects */ @Override public final FluentIterable<E> last(int count) { var remainingElementsCount = getRemainingElementsCount(); var iterator = iterator(); var currentIndex = 0; while (iterator.hasNext()) { iterator.next(); if (currentIndex < remainingElementsCount - count) { iterator.remove(); } currentIndex++; } return this; } /** * Transforms this FluentIterable into a new one containing objects of the type T. * * @param function a function that transforms an instance of E into an instance of T * @param <T> the target type of the transformation * @return a new FluentIterable of the new type */ @Override public final <T> FluentIterable<T> map(Function<? super E, T> function) { var temporaryList = new ArrayList<T>(); this.forEach(e -> temporaryList.add(function.apply(e))); return from(temporaryList); } /** * Collects all remaining objects of this Iterable into a list. * * @return a list with all remaining objects of this Iterable */ @Override public List<E> asList() { return toList(iterable.iterator()); } /** * Constructs FluentIterable from iterable. * * @return a FluentIterable from a given iterable. Calls the SimpleFluentIterable constructor. */ public static <E> FluentIterable<E> from(Iterable<E> iterable) { return new SimpleFluentIterable<>(iterable); } public static <E> FluentIterable<E> fromCopyOf(Iterable<E> iterable) { var copy = FluentIterable.copyToList(iterable); return new SimpleFluentIterable<>(copy); } @Override public Iterator<E> iterator() { return iterable.iterator(); } @Override public void forEach(Consumer<? super E> action) { iterable.forEach(action); } @Override public Spliterator<E> spliterator() { return iterable.spliterator(); } /** * Find the count of remaining objects of current iterable. * * @return the count of remaining objects of the current Iterable */ public final int getRemainingElementsCount() { var counter = 0; for (var ignored : this) { counter++; } return counter; } /** * Collects the remaining objects of the given iterator into a List. * * @return a new List with the remaining objects. */ public static <E> List<E> toList(Iterator<E> iterator) { var copy = new ArrayList<E>(); iterator.forEachRemaining(copy::add); return copy; } }
var iterator = iterator(); var currentCount = 0; while (iterator.hasNext()) { iterator.next(); if (currentCount >= count) { iterator.remove(); } currentCount++; } return this;
1,373
71
1,444
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/flux/src/main/java/com/iluwatar/flux/app/App.java
App
main
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// initialize and wire the system var menuStore = new MenuStore(); Dispatcher.getInstance().registerStore(menuStore); var contentStore = new ContentStore(); Dispatcher.getInstance().registerStore(contentStore); var menuView = new MenuView(); menuStore.registerView(menuView); var contentView = new ContentView(); contentStore.registerView(contentView); // render initial view menuView.render(); contentView.render(); // user clicks another menu item // this triggers action dispatching and eventually causes views to render with new content menuView.itemClicked(MenuItem.COMPANY);
56
164
220
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java
Dispatcher
menuItemSelected
class Dispatcher { private static Dispatcher instance = new Dispatcher(); private final List<Store> stores = new LinkedList<>(); private Dispatcher() { } public static Dispatcher getInstance() { return instance; } public void registerStore(Store store) { stores.add(store); } /** * Menu item selected handler. */ public void menuItemSelected(MenuItem menuItem) {<FILL_FUNCTION_BODY>} private void dispatchAction(Action action) { stores.forEach(store -> store.onAction(action)); } }
dispatchAction(new MenuAction(menuItem)); if (menuItem == MenuItem.COMPANY) { dispatchAction(new ContentAction(Content.COMPANY)); } else { dispatchAction(new ContentAction(Content.PRODUCTS)); }
161
69
230
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java
ContentStore
onAction
class ContentStore extends Store { private Content content = Content.PRODUCTS; @Override public void onAction(Action action) {<FILL_FUNCTION_BODY>} public Content getContent() { return content; } }
if (action.getType().equals(ActionType.CONTENT_CHANGED)) { var contentAction = (ContentAction) action; content = contentAction.getContent(); notifyChange(); }
68
55
123
<methods>public non-sealed void <init>() ,public abstract void onAction(com.iluwatar.flux.action.Action) ,public void registerView(com.iluwatar.flux.view.View) <variables>private final List<com.iluwatar.flux.view.View> views
iluwatar_java-design-patterns
java-design-patterns/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java
MenuStore
onAction
class MenuStore extends Store { private MenuItem selected = MenuItem.HOME; @Override public void onAction(Action action) {<FILL_FUNCTION_BODY>} public MenuItem getSelected() { return selected; } }
if (action.getType().equals(ActionType.MENU_ITEM_SELECTED)) { var menuAction = (MenuAction) action; selected = menuAction.getMenuItem(); notifyChange(); }
68
59
127
<methods>public non-sealed void <init>() ,public abstract void onAction(com.iluwatar.flux.action.Action) ,public void registerView(com.iluwatar.flux.view.View) <variables>private final List<com.iluwatar.flux.view.View> views
iluwatar_java-design-patterns
java-design-patterns/flux/src/main/java/com/iluwatar/flux/view/ContentView.java
ContentView
storeChanged
class ContentView implements View { private Content content = Content.PRODUCTS; @Override public void storeChanged(Store store) {<FILL_FUNCTION_BODY>} @Override public void render() { LOGGER.info(content.toString()); } }
var contentStore = (ContentStore) store; content = contentStore.getContent(); render();
77
29
106
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/flux/src/main/java/com/iluwatar/flux/view/MenuView.java
MenuView
render
class MenuView implements View { private MenuItem selected = MenuItem.HOME; @Override public void storeChanged(Store store) { var menuStore = (MenuStore) store; selected = menuStore.getSelected(); render(); } @Override public void render() {<FILL_FUNCTION_BODY>} public void itemClicked(MenuItem item) { Dispatcher.getInstance().menuItemSelected(item); } }
for (var item : MenuItem.values()) { if (selected.equals(item)) { LOGGER.info("* {}", item); } else { LOGGER.info(item.toString()); } }
121
61
182
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java
AlchemistShop
drinkPotions
class AlchemistShop { private final List<Potion> topShelf; private final List<Potion> bottomShelf; /** * Constructor. */ public AlchemistShop() { var factory = new PotionFactory(); topShelf = List.of( factory.createPotion(PotionType.INVISIBILITY), factory.createPotion(PotionType.INVISIBILITY), factory.createPotion(PotionType.STRENGTH), factory.createPotion(PotionType.HEALING), factory.createPotion(PotionType.INVISIBILITY), factory.createPotion(PotionType.STRENGTH), factory.createPotion(PotionType.HEALING), factory.createPotion(PotionType.HEALING) ); bottomShelf = List.of( factory.createPotion(PotionType.POISON), factory.createPotion(PotionType.POISON), factory.createPotion(PotionType.POISON), factory.createPotion(PotionType.HOLY_WATER), factory.createPotion(PotionType.HOLY_WATER) ); } /** * Get a read-only list of all the items on the top shelf. * * @return The top shelf potions */ public final List<Potion> getTopShelf() { return List.copyOf(this.topShelf); } /** * Get a read-only list of all the items on the bottom shelf. * * @return The bottom shelf potions */ public final List<Potion> getBottomShelf() { return List.copyOf(this.bottomShelf); } /** * Drink all the potions. */ public void drinkPotions() {<FILL_FUNCTION_BODY>} }
LOGGER.info("Drinking top shelf potions"); topShelf.forEach(Potion::drink); LOGGER.info("Drinking bottom shelf potions"); bottomShelf.forEach(Potion::drink);
506
61
567
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/flyweight/src/main/java/com/iluwatar/flyweight/App.java
App
main
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// create the alchemist shop with the potions var alchemistShop = new AlchemistShop(); // a brave visitor enters the alchemist shop and drinks all the potions alchemistShop.drinkPotions();
56
61
117
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java
PotionFactory
createPotion
class PotionFactory { private final Map<PotionType, Potion> potions; public PotionFactory() { potions = new EnumMap<>(PotionType.class); } Potion createPotion(PotionType type) {<FILL_FUNCTION_BODY>} }
var potion = potions.get(type); if (potion == null) { switch (type) { case HEALING -> potion = new HealingPotion(); case HOLY_WATER -> potion = new HolyWaterPotion(); case INVISIBILITY -> potion = new InvisibilityPotion(); case POISON -> potion = new PoisonPotion(); case STRENGTH -> potion = new StrengthPotion(); default -> { } } if (potion != null) { potions.put(type, potion); } } return potion;
90
189
279
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java
FrontController
getCommand
class FrontController { public void handleRequest(String request) { var command = getCommand(request); command.process(); } private Command getCommand(String request) {<FILL_FUNCTION_BODY>} private static Class<?> getCommandClass(String request) { try { return Class.forName("com.iluwatar.front.controller." + request + "Command"); } catch (ClassNotFoundException e) { return UnknownCommand.class; } } }
var commandClass = getCommandClass(request); try { return (Command) commandClass.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new ApplicationException(e); }
133
57
190
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/game-loop/src/main/java/com/iluwatar/gameloop/App.java
App
main
class App { /** * Each type of game loop will run for 2 seconds. */ private static final int GAME_LOOP_DURATION_TIME = 2000; /** * Program entry point. * @param args runtime arguments */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
try { LOGGER.info("Start frame-based game loop:"); var frameBasedGameLoop = new FrameBasedGameLoop(); frameBasedGameLoop.run(); Thread.sleep(GAME_LOOP_DURATION_TIME); frameBasedGameLoop.stop(); LOGGER.info("Stop frame-based game loop."); LOGGER.info("Start variable-step game loop:"); var variableStepGameLoop = new VariableStepGameLoop(); variableStepGameLoop.run(); Thread.sleep(GAME_LOOP_DURATION_TIME); variableStepGameLoop.stop(); LOGGER.info("Stop variable-step game loop."); LOGGER.info("Start fixed-step game loop:"); var fixedStepGameLoop = new FixedStepGameLoop(); fixedStepGameLoop.run(); Thread.sleep(GAME_LOOP_DURATION_TIME); fixedStepGameLoop.stop(); LOGGER.info("Stop variable-step game loop."); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); }
98
274
372
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/game-loop/src/main/java/com/iluwatar/gameloop/FixedStepGameLoop.java
FixedStepGameLoop
processGameLoop
class FixedStepGameLoop extends GameLoop { /** * 20 ms per frame = 50 FPS. */ private static final long MS_PER_FRAME = 20; @Override protected void processGameLoop() {<FILL_FUNCTION_BODY>} protected void update() { controller.moveBullet(0.5f * MS_PER_FRAME / 1000); } }
var previousTime = System.currentTimeMillis(); var lag = 0L; while (isGameRunning()) { var currentTime = System.currentTimeMillis(); var elapsedTime = currentTime - previousTime; previousTime = currentTime; lag += elapsedTime; processInput(); while (lag >= MS_PER_FRAME) { update(); lag -= MS_PER_FRAME; } render(); }
114
123
237
<methods>public boolean isGameRunning() ,public void run() ,public void stop() <variables>protected final non-sealed com.iluwatar.gameloop.GameController controller,protected final Logger logger,protected volatile com.iluwatar.gameloop.GameStatus status
iluwatar_java-design-patterns
java-design-patterns/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java
GameLoop
processInput
class GameLoop { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected volatile GameStatus status; protected final GameController controller; /** * Initialize game status to be stopped. */ protected GameLoop() { controller = new GameController(); status = GameStatus.STOPPED; } /** * Run game loop. */ public void run() { status = GameStatus.RUNNING; Thread gameThread = new Thread(this::processGameLoop); gameThread.start(); } /** * Stop game loop. */ public void stop() { status = GameStatus.STOPPED; } /** * Check if game is running or not. * * @return {@code true} if the game is running. */ public boolean isGameRunning() { return status == GameStatus.RUNNING; } /** * Handle any user input that has happened since the last call. In order to * simulate the situation in real-life game, here we add a random time lag. * The time lag ranges from 50 ms to 250 ms. */ protected void processInput() {<FILL_FUNCTION_BODY>} /** * Render game frames to screen. Here we print bullet position to simulate * this process. */ protected void render() { var position = controller.getBulletPosition(); logger.info("Current bullet position: {}", position); } /** * execute game loop logic. */ protected abstract void processGameLoop(); }
try { var lag = new SecureRandom().nextInt(200) + 50; Thread.sleep(lag); } catch (InterruptedException e) { logger.error(e.getMessage()); /* Clean up whatever needs to be handled before interrupting */ Thread.currentThread().interrupt(); }
423
86
509
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/game-loop/src/main/java/com/iluwatar/gameloop/VariableStepGameLoop.java
VariableStepGameLoop
processGameLoop
class VariableStepGameLoop extends GameLoop { @Override protected void processGameLoop() {<FILL_FUNCTION_BODY>} protected void update(Long elapsedTime) { controller.moveBullet(0.5f * elapsedTime / 1000); } }
var lastFrameTime = System.currentTimeMillis(); while (isGameRunning()) { processInput(); var currentFrameTime = System.currentTimeMillis(); var elapsedTime = currentFrameTime - lastFrameTime; update(elapsedTime); lastFrameTime = currentFrameTime; render(); }
80
85
165
<methods>public boolean isGameRunning() ,public void run() ,public void stop() <variables>protected final non-sealed com.iluwatar.gameloop.GameController controller,protected final Logger logger,protected volatile com.iluwatar.gameloop.GameStatus status
iluwatar_java-design-patterns
java-design-patterns/gateway/src/main/java/com/iluwatar/gateway/App.java
App
main
class App { /** * Simulate an application calling external services. */ public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
GatewayFactory gatewayFactory = new GatewayFactory(); // Register different gateways gatewayFactory.registerGateway("ServiceA", new ExternalServiceA()); gatewayFactory.registerGateway("ServiceB", new ExternalServiceB()); gatewayFactory.registerGateway("ServiceC", new ExternalServiceC()); // Use an executor service for execution Gateway serviceA = gatewayFactory.getGateway("ServiceA"); Gateway serviceB = gatewayFactory.getGateway("ServiceB"); Gateway serviceC = gatewayFactory.getGateway("ServiceC"); // Execute external services try { serviceA.execute(); serviceB.execute(); serviceC.execute(); } catch (ThreadDeath e) { LOGGER.info("Interrupted!" + e); throw e; }
49
211
260
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceA.java
ExternalServiceA
execute
class ExternalServiceA implements Gateway { @Override public void execute() throws Exception {<FILL_FUNCTION_BODY>} }
LOGGER.info("Executing Service A"); // Simulate a time-consuming task Thread.sleep(1000);
37
37
74
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceB.java
ExternalServiceB
execute
class ExternalServiceB implements Gateway { @Override public void execute() throws Exception {<FILL_FUNCTION_BODY>} }
LOGGER.info("Executing Service B"); // Simulate a time-consuming task Thread.sleep(1000);
37
37
74
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceC.java
ExternalServiceC
error
class ExternalServiceC implements Gateway { @Override public void execute() throws Exception { LOGGER.info("Executing Service C"); // Simulate a time-consuming task Thread.sleep(1000); } public void error() throws Exception {<FILL_FUNCTION_BODY>} }
// Simulate an exception throw new RuntimeException("Service C encountered an error");
84
23
107
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java
App
main
class App { /** * Example pattern execution. * * @param args - command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
var guardedQueue = new GuardedQueue(); var executorService = Executors.newFixedThreadPool(3); //here we create first thread which is supposed to get from guardedQueue executorService.execute(guardedQueue::get); // here we wait two seconds to show that the thread which is trying // to get from guardedQueue will be waiting try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } // now we execute second thread which will put number to guardedQueue // and notify first thread that it could get executorService.execute(() -> guardedQueue.put(20)); executorService.shutdown(); try { executorService.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); }
57
232
289
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java
GuardedQueue
get
class GuardedQueue { private final Queue<Integer> sourceList; public GuardedQueue() { this.sourceList = new LinkedList<>(); } /** * Get the last element of the queue is exists. * * @return last element of a queue if queue is not empty */ public synchronized Integer get() {<FILL_FUNCTION_BODY>} /** * Put a value in the queue. * * @param e number which we want to put to our queue */ public synchronized void put(Integer e) { LOGGER.info("putting"); sourceList.add(e); LOGGER.info("notifying"); notify(); } }
while (sourceList.isEmpty()) { try { LOGGER.info("waiting"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } LOGGER.info("getting"); return sourceList.peek();
186
75
261
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java
App
main
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} /** * ArithmeticSumTask. */ static class ArithmeticSumTask implements AsyncTask<Long> { private final long numberOfElements; public ArithmeticSumTask(long numberOfElements) { this.numberOfElements = numberOfElements; } /* * This is the long running task that is performed in background. In our example the long * running task is calculating arithmetic sum with artificial delay. */ @Override public Long call() throws Exception { return ap(numberOfElements); } /* * This will be called in context of the main thread where some validations can be done * regarding the inputs. Such as it must be greater than 0. It's a small computation which can * be performed in main thread. If we did validated the input in background thread then we pay * the cost of context switching which is much more than validating it in main thread. */ @Override public void onPreCall() { if (numberOfElements < 0) { throw new IllegalArgumentException("n is less than 0"); } } @Override public void onPostCall(Long result) { // Handle the result of computation LOGGER.info(result.toString()); } @Override public void onError(Throwable throwable) { throw new IllegalStateException("Should not occur"); } } private static long ap(long i) { try { Thread.sleep(i); } catch (InterruptedException e) { LOGGER.error("Exception caught.", e); } return i * (i + 1) / 2; } }
var service = new AsynchronousService(new LinkedBlockingQueue<>()); /* * A new task to calculate sum is received but as this is main thread, it should not block. So * it passes it to the asynchronous task layer to compute and proceeds with handling other * incoming requests. This is particularly useful when main thread is waiting on Socket to * receive new incoming requests and does not wait for particular request to be completed before * responding to new request. */ service.execute(new ArithmeticSumTask(1000)); /* * New task received, lets pass that to async layer for computation. So both requests will be * executed in parallel. */ service.execute(new ArithmeticSumTask(500)); service.execute(new ArithmeticSumTask(2000)); service.execute(new ArithmeticSumTask(1)); service.close();
472
220
692
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java
AsynchronousService
execute
class AsynchronousService { /* * This represents the queuing layer as well as synchronous layer of the pattern. The thread pool * contains worker threads which execute the tasks in blocking/synchronous manner. Long running * tasks should be performed in the background which does not affect the performance of main * thread. */ private final ExecutorService service; /** * Creates an asynchronous service using {@code workQueue} as communication channel between * asynchronous layer and synchronous layer. Different types of queues such as Priority queue, can * be used to control the pattern of communication between the layers. */ public AsynchronousService(BlockingQueue<Runnable> workQueue) { service = new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, workQueue); } /** * A non-blocking method which performs the task provided in background and returns immediately. * * <p>On successful completion of task the result is posted back using callback method {@link * AsyncTask#onPostCall(Object)}, if task execution is unable to complete normally due to some * exception then the reason for error is posted back using callback method {@link * AsyncTask#onError(Throwable)}. * * <p>NOTE: The results are posted back in the context of background thread in this * implementation. */ public <T> void execute(final AsyncTask<T> task) {<FILL_FUNCTION_BODY>} /** * Stops the pool of workers. This is a blocking call to wait for all tasks to be completed. */ public void close() { service.shutdown(); try { service.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException ie) { LOGGER.error("Error waiting for executor service shutdown!"); } } }
try { // some small tasks such as validation can be performed here. task.onPreCall(); } catch (Exception e) { task.onError(e); return; } service.submit(new FutureTask<T>(task) { @Override protected void done() { super.done(); try { /* * called in context of background thread. There is other variant possible where result is * posted back and sits in the queue of caller thread which then picks it up for * processing. An example of such a system is Android OS, where the UI elements can only * be updated using UI thread. So result must be posted back in UI thread. */ task.onPostCall(get()); } catch (InterruptedException e) { // should not occur } catch (ExecutionException e) { task.onError(e.getCause()); } } });
471
235
706
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/AsynchronousHealthChecker.java
AsynchronousHealthChecker
shutdown
class AsynchronousHealthChecker { /** A scheduled executor service used to execute health checks in a separate thread. */ private final ScheduledExecutorService healthCheckExecutor = Executors.newSingleThreadScheduledExecutor(); private static final String HEALTH_CHECK_TIMEOUT_MESSAGE = "Health check timed out"; private static final String HEALTH_CHECK_FAILED_MESSAGE = "Health check failed"; /** * Performs a health check asynchronously using the provided health check logic with a specified * timeout. * * @param healthCheck the health check logic supplied as a {@code Supplier<Health>} * @param timeoutInSeconds the maximum time to wait for the health check to complete, in seconds * @return a {@code CompletableFuture<Health>} object that represents the result of the health * check */ public CompletableFuture<Health> performCheck( Supplier<Health> healthCheck, long timeoutInSeconds) { CompletableFuture<Health> future = CompletableFuture.supplyAsync(healthCheck, healthCheckExecutor); // Schedule a task to enforce the timeout healthCheckExecutor.schedule( () -> { if (!future.isDone()) { LOGGER.error(HEALTH_CHECK_TIMEOUT_MESSAGE); future.completeExceptionally(new TimeoutException(HEALTH_CHECK_TIMEOUT_MESSAGE)); } }, timeoutInSeconds, TimeUnit.SECONDS); return future.handle( (result, throwable) -> { if (throwable != null) { LOGGER.error(HEALTH_CHECK_FAILED_MESSAGE, throwable); // Check if the throwable is a TimeoutException or caused by a TimeoutException Throwable rootCause = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (!(rootCause instanceof TimeoutException)) { LOGGER.error(HEALTH_CHECK_FAILED_MESSAGE, rootCause); return Health.down().withException(rootCause).build(); } else { LOGGER.error(HEALTH_CHECK_TIMEOUT_MESSAGE, rootCause); // If it is a TimeoutException, rethrow it wrapped in a CompletionException throw new CompletionException(rootCause); } } else { return result; } }); } /** * Checks whether the health check executor service has terminated completely. This method waits * for the executor service to finish all its tasks within a specified timeout. If the timeout is * reached before all tasks are completed, the method returns `true`; otherwise, it returns * `false`. * * @throws InterruptedException if the current thread is interrupted while waiting for the * executor service to terminate */ private boolean awaitTerminationWithTimeout() throws InterruptedException { boolean isTerminationIncomplete = !healthCheckExecutor.awaitTermination(5, TimeUnit.SECONDS); LOGGER.info("Termination status: {}", isTerminationIncomplete); // Await termination and return true if termination is incomplete (timeout elapsed) return isTerminationIncomplete; } /** Shuts down the executor service, allowing in-flight tasks to complete. */ @PreDestroy public void shutdown() {<FILL_FUNCTION_BODY>} }
try { // Wait a while for existing tasks to terminate if (awaitTerminationWithTimeout()) { LOGGER.info("Health check executor did not terminate in time"); // Attempt to cancel currently executing tasks healthCheckExecutor.shutdownNow(); // Wait again for tasks to respond to being cancelled if (awaitTerminationWithTimeout()) { LOGGER.error("Health check executor did not terminate"); } } } catch (InterruptedException ie) { // Preserve interrupt status Thread.currentThread().interrupt(); // (Re-)Cancel if current thread also interrupted healthCheckExecutor.shutdownNow(); // Log the stack trace for interrupted exception LOGGER.error("Shutdown of the health check executor was interrupted", ie); }
865
201
1,066
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/CpuHealthIndicator.java
CpuHealthIndicator
health
class CpuHealthIndicator implements HealthIndicator { /** The operating system MXBean used to gather CPU health information. */ private OperatingSystemMXBean osBean; /** Initializes the {@link OperatingSystemMXBean} instance. */ @PostConstruct public void init() { this.osBean = ManagementFactory.getOperatingSystemMXBean(); } /** * The system CPU load threshold. If the system CPU load is above this threshold, the health * indicator will return a `down` health status. */ @Value("${cpu.system.load.threshold:80.0}") private double systemCpuLoadThreshold; /** * The process CPU load threshold. If the process CPU load is above this threshold, the health * indicator will return a `down` health status. */ @Value("${cpu.process.load.threshold:50.0}") private double processCpuLoadThreshold; /** * The load average threshold. If the load average is above this threshold, the health indicator * will return an `up` health status with a warning message. */ @Value("${cpu.load.average.threshold:0.75}") private double loadAverageThreshold; /** * The warning message to include in the health indicator's response when the load average is high * but not exceeding the threshold. */ @Value("${cpu.warning.message:High load average}") private String defaultWarningMessage; private static final String ERROR_MESSAGE = "error"; private static final String HIGH_SYSTEM_CPU_LOAD_MESSAGE = "High system CPU load: {}"; private static final String HIGH_PROCESS_CPU_LOAD_MESSAGE = "High process CPU load: {}"; private static final String HIGH_LOAD_AVERAGE_MESSAGE = "High load average: {}"; private static final String HIGH_PROCESS_CPU_LOAD_MESSAGE_WITHOUT_PARAM = "High process CPU load"; private static final String HIGH_SYSTEM_CPU_LOAD_MESSAGE_WITHOUT_PARAM = "High system CPU load"; private static final String HIGH_LOAD_AVERAGE_MESSAGE_WITHOUT_PARAM = "High load average"; /** * Checks the health of the system's CPU and returns a health indicator object. * * @return a health indicator object */ @Override public Health health() {<FILL_FUNCTION_BODY>} }
if (!(osBean instanceof com.sun.management.OperatingSystemMXBean sunOsBean)) { LOGGER.error("Unsupported operating system MXBean: {}", osBean.getClass().getName()); return Health.unknown() .withDetail(ERROR_MESSAGE, "Unsupported operating system MXBean") .build(); } double systemCpuLoad = sunOsBean.getCpuLoad() * 100; double processCpuLoad = sunOsBean.getProcessCpuLoad() * 100; int availableProcessors = sunOsBean.getAvailableProcessors(); double loadAverage = sunOsBean.getSystemLoadAverage(); Map<String, Object> details = new HashMap<>(); details.put("timestamp", Instant.now()); details.put("systemCpuLoad", String.format("%.2f%%", systemCpuLoad)); details.put("processCpuLoad", String.format("%.2f%%", processCpuLoad)); details.put("availableProcessors", availableProcessors); details.put("loadAverage", loadAverage); if (systemCpuLoad > systemCpuLoadThreshold) { LOGGER.error(HIGH_SYSTEM_CPU_LOAD_MESSAGE, systemCpuLoad); return Health.down() .withDetails(details) .withDetail(ERROR_MESSAGE, HIGH_SYSTEM_CPU_LOAD_MESSAGE_WITHOUT_PARAM) .build(); } else if (processCpuLoad > processCpuLoadThreshold) { LOGGER.error(HIGH_PROCESS_CPU_LOAD_MESSAGE, processCpuLoad); return Health.down() .withDetails(details) .withDetail(ERROR_MESSAGE, HIGH_PROCESS_CPU_LOAD_MESSAGE_WITHOUT_PARAM) .build(); } else if (loadAverage > (availableProcessors * loadAverageThreshold)) { LOGGER.error(HIGH_LOAD_AVERAGE_MESSAGE, loadAverage); return Health.up() .withDetails(details) .withDetail(ERROR_MESSAGE, HIGH_LOAD_AVERAGE_MESSAGE_WITHOUT_PARAM) .build(); } else { return Health.up().withDetails(details).build(); }
638
587
1,225
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/CustomHealthIndicator.java
CustomHealthIndicator
health
class CustomHealthIndicator implements HealthIndicator { private final AsynchronousHealthChecker healthChecker; private final CacheManager cacheManager; private final HealthCheckRepository healthCheckRepository; @Value("${health.check.timeout:10}") private long timeoutInSeconds; /** * Perform a health check and cache the result. * * @return the health status of the application * @throws HealthCheckInterruptedException if the health check is interrupted */ @Override @Cacheable(value = "health-check", unless = "#result.status == 'DOWN'") public Health health() {<FILL_FUNCTION_BODY>} /** * Checks the health of the database by querying for a simple constant value expected from the * database. * * @return Health indicating UP if the database returns the constant correctly, otherwise DOWN. */ private Health check() { Integer result = healthCheckRepository.checkHealth(); boolean databaseIsUp = result != null && result == 1; LOGGER.info("Health check result: {}", databaseIsUp); return databaseIsUp ? Health.up().withDetail("database", "reachable").build() : Health.down().withDetail("database", "unreachable").build(); } /** * Evicts all entries from the health check cache. This is scheduled to run at a fixed rate * defined in the application properties. */ @Scheduled(fixedRateString = "${health.check.cache.evict.interval:60000}") public void evictHealthCache() { LOGGER.info("Evicting health check cache"); try { Cache healthCheckCache = cacheManager.getCache("health-check"); LOGGER.info("Health check cache: {}", healthCheckCache); if (healthCheckCache != null) { healthCheckCache.clear(); } } catch (Exception e) { LOGGER.error("Failed to evict health check cache", e); } } }
LOGGER.info("Performing health check"); CompletableFuture<Health> healthFuture = healthChecker.performCheck(this::check, timeoutInSeconds); try { return healthFuture.get(timeoutInSeconds, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOGGER.error("Health check interrupted", e); throw new HealthCheckInterruptedException(e); } catch (Exception e) { LOGGER.error("Health check failed", e); return Health.down(e).build(); }
515
151
666
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/DatabaseTransactionHealthIndicator.java
DatabaseTransactionHealthIndicator
health
class DatabaseTransactionHealthIndicator implements HealthIndicator { /** A repository for performing health checks on the database. */ private final HealthCheckRepository healthCheckRepository; /** An asynchronous health checker used to execute health checks in a separate thread. */ private final AsynchronousHealthChecker asynchronousHealthChecker; /** A retry template used to retry the test transaction if it fails due to a transient error. */ private final RetryTemplate retryTemplate; /** * The timeout in seconds for the health check. If the health check does not complete within this * timeout, it will be considered timed out and will return {@link Health#down()}. */ @Value("${health.check.timeout:10}") private long timeoutInSeconds; /** * Performs a health check by attempting to perform a test transaction with retry support. * * @return the health status of the database transactions */ @Override public Health health() {<FILL_FUNCTION_BODY>} }
LOGGER.info("Calling performCheck with timeout {}", timeoutInSeconds); Supplier<Health> dbTransactionCheck = () -> { try { healthCheckRepository.performTestTransaction(); return Health.up().build(); } catch (Exception e) { LOGGER.error("Database transaction health check failed", e); return Health.down(e).build(); } }; try { return asynchronousHealthChecker.performCheck(dbTransactionCheck, timeoutInSeconds).get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error("Database transaction health check timed out or was interrupted", e); Thread.currentThread().interrupt(); return Health.down(e).build(); }
255
192
447
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/GarbageCollectionHealthIndicator.java
GarbageCollectionHealthIndicator
health
class GarbageCollectionHealthIndicator implements HealthIndicator { /** * The memory usage threshold above which a warning message is included in the health check * report. */ @Value("${memory.usage.threshold:0.8}") private double memoryUsageThreshold; /** * Performs a health check by gathering garbage collection metrics and evaluating the overall * health of the garbage collection system. * * @return a {@link Health} object representing the health status of the garbage collection system */ @Override public Health health() {<FILL_FUNCTION_BODY>} /** * Creates details for the given garbage collector, including collection count, collection time, * and memory pool information. * * @param gcBean The garbage collector MXBean * @param memoryPoolMxBeans List of memory pool MXBeans * @return Map containing details for the garbage collector */ private Map<String, String> createCollectorDetails( GarbageCollectorMXBean gcBean, List<MemoryPoolMXBean> memoryPoolMxBeans) { Map<String, String> collectorDetails = new HashMap<>(); long count = gcBean.getCollectionCount(); long time = gcBean.getCollectionTime(); collectorDetails.put("count", String.format("%d", count)); collectorDetails.put("time", String.format("%dms", time)); String[] memoryPoolNames = gcBean.getMemoryPoolNames(); List<String> memoryPoolNamesList = Arrays.asList(memoryPoolNames); if (!memoryPoolNamesList.isEmpty()) { addMemoryPoolDetails(collectorDetails, memoryPoolMxBeans, memoryPoolNamesList); } else { LOGGER.error("Garbage collector '{}' does not have any memory pools", gcBean.getName()); } return collectorDetails; } /** * Adds memory pool details to the collector details. * * @param collectorDetails Map containing details for the garbage collector * @param memoryPoolMxBeans List of memory pool MXBeans * @param memoryPoolNamesList List of memory pool names associated with the garbage collector */ private void addMemoryPoolDetails( Map<String, String> collectorDetails, List<MemoryPoolMXBean> memoryPoolMxBeans, List<String> memoryPoolNamesList) { for (MemoryPoolMXBean memoryPoolmxbean : memoryPoolMxBeans) { if (memoryPoolNamesList.contains(memoryPoolmxbean.getName())) { double memoryUsage = memoryPoolmxbean.getUsage().getUsed() / (double) memoryPoolmxbean.getUsage().getMax(); if (memoryUsage > memoryUsageThreshold) { collectorDetails.put( "warning", String.format( "Memory pool '%s' usage is high (%2f%%)", memoryPoolmxbean.getName(), memoryUsage)); } collectorDetails.put( "memoryPools", String.format("%s: %s%%", memoryPoolmxbean.getName(), memoryUsage)); } } } /** * Retrieves the list of garbage collector MXBeans using ManagementFactory. * * @return a list of {@link GarbageCollectorMXBean} objects representing the garbage collectors */ protected List<GarbageCollectorMXBean> getGarbageCollectorMxBeans() { return ManagementFactory.getGarbageCollectorMXBeans(); } /** * Retrieves the list of memory pool MXBeans using ManagementFactory. * * @return a list of {@link MemoryPoolMXBean} objects representing the memory pools */ protected List<MemoryPoolMXBean> getMemoryPoolMxBeans() { return ManagementFactory.getMemoryPoolMXBeans(); } }
List<GarbageCollectorMXBean> gcBeans = getGarbageCollectorMxBeans(); List<MemoryPoolMXBean> memoryPoolMxBeans = getMemoryPoolMxBeans(); Map<String, Map<String, String>> gcDetails = new HashMap<>(); for (GarbageCollectorMXBean gcBean : gcBeans) { Map<String, String> collectorDetails = createCollectorDetails(gcBean, memoryPoolMxBeans); gcDetails.put(gcBean.getName(), collectorDetails); } return Health.up().withDetails(gcDetails).build();
968
165
1,133
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/HealthCheckRepository.java
HealthCheckRepository
performTestTransaction
class HealthCheckRepository { private static final String HEALTH_CHECK_OK = "OK"; @PersistenceContext private EntityManager entityManager; /** * Checks the health of the database connection by executing a simple query that should always * return 1 if the connection is healthy. * * @return 1 if the database connection is healthy, or null otherwise */ public Integer checkHealth() { try { return (Integer) entityManager.createNativeQuery("SELECT 1").getSingleResult(); } catch (Exception e) { LOGGER.error("Health check query failed", e); throw e; } } /** * Performs a test transaction by writing a record to the `health_check` table, reading it back, * and then deleting it. If any of these operations fail, an exception is thrown. * * @throws Exception if the test transaction fails */ @Transactional public void performTestTransaction() {<FILL_FUNCTION_BODY>} }
try { HealthCheck healthCheck = new HealthCheck(); healthCheck.setStatus(HEALTH_CHECK_OK); entityManager.persist(healthCheck); entityManager.flush(); HealthCheck retrievedHealthCheck = entityManager.find(HealthCheck.class, healthCheck.getId()); entityManager.remove(retrievedHealthCheck); } catch (Exception e) { LOGGER.error("Test transaction failed", e); throw e; }
257
118
375
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/MemoryHealthIndicator.java
MemoryHealthIndicator
checkMemory
class MemoryHealthIndicator implements HealthIndicator { private final AsynchronousHealthChecker asynchronousHealthChecker; /** The timeout in seconds for the health check. */ @Value("${health.check.timeout:10}") private long timeoutInSeconds; /** * The memory usage threshold in percentage. If the memory usage is less than this threshold, the * health status is reported as UP. Otherwise, the health status is reported as DOWN. */ @Value("${health.check.memory.threshold:0.9}") private double memoryThreshold; /** * Performs a health check by checking the memory usage of the application. * * @return the health status of the application */ public Health checkMemory() {<FILL_FUNCTION_BODY>} /** * Retrieves the health status of the application by checking the memory usage. * * @return the health status of the application */ @Override public Health health() { return checkMemory(); } }
Supplier<Health> memoryCheck = () -> { MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean(); MemoryUsage heapMemoryUsage = memoryMxBean.getHeapMemoryUsage(); long maxMemory = heapMemoryUsage.getMax(); long usedMemory = heapMemoryUsage.getUsed(); double memoryUsage = (double) usedMemory / maxMemory; String format = String.format("%.2f%% of %d max", memoryUsage * 100, maxMemory); if (memoryUsage < memoryThreshold) { LOGGER.info("Memory usage is below threshold: {}", format); return Health.up().withDetail("memory usage", format).build(); } else { return Health.down().withDetail("memory usage", format).build(); } }; try { CompletableFuture<Health> future = asynchronousHealthChecker.performCheck(memoryCheck, timeoutInSeconds); return future.get(); } catch (InterruptedException e) { LOGGER.error("Health check interrupted", e); Thread.currentThread().interrupt(); return Health.down().withDetail("error", "Health check interrupted").build(); } catch (ExecutionException e) { LOGGER.error("Health check failed", e); Throwable cause = e.getCause() == null ? e : e.getCause(); return Health.down().withDetail("error", cause.toString()).build(); }
266
367
633
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/health-check/src/main/java/com/iluwatar/health/check/RetryConfig.java
RetryConfig
retryTemplate
class RetryConfig { /** The backoff period in milliseconds to wait between retry attempts. */ @Value("${retry.backoff.period:2000}") private long backOffPeriod; /** The maximum number of retry attempts for health check operations. */ @Value("${retry.max.attempts:3}") private int maxAttempts; /** * Creates a retry template with the configured backoff period and maximum number of attempts. * * @return a retry template */ @Bean public RetryTemplate retryTemplate() {<FILL_FUNCTION_BODY>} }
RetryTemplate retryTemplate = new RetryTemplate(); FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy(); fixedBackOffPolicy.setBackOffPeriod(backOffPeriod); // wait 2 seconds between retries retryTemplate.setBackOffPolicy(fixedBackOffPolicy); SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); retryPolicy.setMaxAttempts(maxAttempts); // retry a max of 3 attempts retryTemplate.setRetryPolicy(retryPolicy); return retryTemplate;
169
141
310
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java
App
main
class App { /** * Program entry point. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
var injector = Guice.createInjector(new LotteryTestingModule()); // start new lottery round var administration = injector.getInstance(LotteryAdministration.class); administration.resetLottery(); // submit some lottery tickets var service = injector.getInstance(LotteryService.class); SampleData.submitTickets(service, 20); // perform lottery administration.performLottery();
44
120
164
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java
ConsoleAdministration
main
class ConsoleAdministration { /** * Program entry point. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} private static void printMainMenu() { LOGGER.info(""); LOGGER.info("### Lottery Administration Console ###"); LOGGER.info("(1) Show all submitted tickets"); LOGGER.info("(2) Perform lottery draw"); LOGGER.info("(3) Reset lottery ticket database"); LOGGER.info("(4) Exit"); } private static String readString(Scanner scanner) { LOGGER.info("> "); return scanner.next(); } }
MongoConnectionPropertiesLoader.load(); var injector = Guice.createInjector(new LotteryModule()); var administration = injector.getInstance(LotteryAdministration.class); var service = injector.getInstance(LotteryService.class); SampleData.submitTickets(service, 20); var consoleAdministration = new ConsoleAdministrationSrvImpl(administration, LOGGER); try (var scanner = new Scanner(System.in)) { var exit = false; while (!exit) { printMainMenu(); var cmd = readString(scanner); if ("1".equals(cmd)) { consoleAdministration.getAllSubmittedTickets(); } else if ("2".equals(cmd)) { consoleAdministration.performLottery(); } else if ("3".equals(cmd)) { consoleAdministration.resetLottery(); } else if ("4".equals(cmd)) { exit = true; } else { LOGGER.info("Unknown command: {}", cmd); } } }
180
278
458
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java
ConsoleAdministrationSrvImpl
performLottery
class ConsoleAdministrationSrvImpl implements ConsoleAdministrationSrv { private final LotteryAdministration administration; private final Logger logger; /** * Constructor. */ public ConsoleAdministrationSrvImpl(LotteryAdministration administration, Logger logger) { this.administration = administration; this.logger = logger; } @Override public void getAllSubmittedTickets() { administration.getAllSubmittedTickets() .forEach((k, v) -> logger.info("Key: {}, Value: {}", k, v)); } @Override public void performLottery() {<FILL_FUNCTION_BODY>} @Override public void resetLottery() { administration.resetLottery(); logger.info("The lottery ticket database was cleared."); } }
var numbers = administration.performLottery(); logger.info("The winning numbers: {}", numbers.getNumbersAsString()); logger.info("Time to reset the database for next round, eh?");
221
55
276
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java
InMemoryBank
transferFunds
class InMemoryBank implements WireTransfers { private static final Map<String, Integer> accounts = new HashMap<>(); static { accounts .put(LotteryConstants.SERVICE_BANK_ACCOUNT, LotteryConstants.SERVICE_BANK_ACCOUNT_BALANCE); } @Override public void setFunds(String bankAccount, int amount) { accounts.put(bankAccount, amount); } @Override public int getFunds(String bankAccount) { return accounts.getOrDefault(bankAccount, 0); } @Override public boolean transferFunds(int amount, String sourceAccount, String destinationAccount) {<FILL_FUNCTION_BODY>} }
if (accounts.getOrDefault(sourceAccount, 0) >= amount) { accounts.put(sourceAccount, accounts.get(sourceAccount) - amount); accounts.put(destinationAccount, accounts.get(destinationAccount) + amount); return true; } else { return false; }
194
82
276
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java
MongoBank
transferFunds
class MongoBank implements WireTransfers { private static final String DEFAULT_DB = "lotteryDB"; private static final String DEFAULT_ACCOUNTS_COLLECTION = "accounts"; private MongoClient mongoClient; private MongoDatabase database; private MongoCollection<Document> accountsCollection; /** * Constructor. */ public MongoBank() { connect(); } /** * Constructor accepting parameters. */ public MongoBank(String dbName, String accountsCollectionName) { connect(dbName, accountsCollectionName); } /** * Connect to database with default parameters. */ public void connect() { connect(DEFAULT_DB, DEFAULT_ACCOUNTS_COLLECTION); } /** * Connect to database with given parameters. */ public void connect(String dbName, String accountsCollectionName) { if (mongoClient != null) { mongoClient.close(); } mongoClient = new MongoClient(System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); database = mongoClient.getDatabase(dbName); accountsCollection = database.getCollection(accountsCollectionName); } /** * Get mongo client. * * @return mongo client */ public MongoClient getMongoClient() { return mongoClient; } /** * Get mongo database. * * @return mongo database */ public MongoDatabase getMongoDatabase() { return database; } /** * Get accounts collection. * * @return accounts collection */ public MongoCollection<Document> getAccountsCollection() { return accountsCollection; } @Override public void setFunds(String bankAccount, int amount) { var search = new Document("_id", bankAccount); var update = new Document("_id", bankAccount).append("funds", amount); var updateOptions = new UpdateOptions().upsert(true); accountsCollection.updateOne(search, new Document("$set", update), updateOptions); } @Override public int getFunds(String bankAccount) { return accountsCollection .find(new Document("_id", bankAccount)) .limit(1) .into(new ArrayList<>()) .stream() .findFirst() .map(x -> x.getInteger("funds")) .orElse(0); } @Override public boolean transferFunds(int amount, String sourceAccount, String destinationAccount) {<FILL_FUNCTION_BODY>} }
var sourceFunds = getFunds(sourceAccount); if (sourceFunds < amount) { return false; } else { var destFunds = getFunds(destinationAccount); setFunds(sourceAccount, sourceFunds - amount); setFunds(destinationAccount, destFunds + amount); return true; }
702
101
803
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java
InMemoryTicketRepository
save
class InMemoryTicketRepository implements LotteryTicketRepository { private static final Map<LotteryTicketId, LotteryTicket> tickets = new HashMap<>(); @Override public Optional<LotteryTicket> findById(LotteryTicketId id) { return Optional.ofNullable(tickets.get(id)); } @Override public Optional<LotteryTicketId> save(LotteryTicket ticket) {<FILL_FUNCTION_BODY>} @Override public Map<LotteryTicketId, LotteryTicket> findAll() { return tickets; } @Override public void deleteAll() { tickets.clear(); } }
var id = new LotteryTicketId(); tickets.put(id, ticket); return Optional.of(id);
184
34
218
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java
MongoTicketRepository
getNextId
class MongoTicketRepository implements LotteryTicketRepository { private static final String DEFAULT_DB = "lotteryDB"; private static final String DEFAULT_TICKETS_COLLECTION = "lotteryTickets"; private static final String DEFAULT_COUNTERS_COLLECTION = "counters"; private static final String TICKET_ID = "ticketId"; private MongoClient mongoClient; private MongoDatabase database; private MongoCollection<Document> ticketsCollection; private MongoCollection<Document> countersCollection; /** * Constructor. */ public MongoTicketRepository() { connect(); } /** * Constructor accepting parameters. */ public MongoTicketRepository(String dbName, String ticketsCollectionName, String countersCollectionName) { connect(dbName, ticketsCollectionName, countersCollectionName); } /** * Connect to database with default parameters. */ public void connect() { connect(DEFAULT_DB, DEFAULT_TICKETS_COLLECTION, DEFAULT_COUNTERS_COLLECTION); } /** * Connect to database with given parameters. */ public void connect(String dbName, String ticketsCollectionName, String countersCollectionName) { if (mongoClient != null) { mongoClient.close(); } mongoClient = new MongoClient(System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); database = mongoClient.getDatabase(dbName); ticketsCollection = database.getCollection(ticketsCollectionName); countersCollection = database.getCollection(countersCollectionName); if (countersCollection.countDocuments() <= 0) { initCounters(); } } private void initCounters() { var doc = new Document("_id", TICKET_ID).append("seq", 1); countersCollection.insertOne(doc); } /** * Get next ticket id. * * @return next ticket id */ public int getNextId() {<FILL_FUNCTION_BODY>} /** * Get tickets collection. * * @return tickets collection */ public MongoCollection<Document> getTicketsCollection() { return ticketsCollection; } /** * Get counters collection. * * @return counters collection */ public MongoCollection<Document> getCountersCollection() { return countersCollection; } @Override public Optional<LotteryTicket> findById(LotteryTicketId id) { return ticketsCollection .find(new Document(TICKET_ID, id.getId())) .limit(1) .into(new ArrayList<>()) .stream() .findFirst() .map(this::docToTicket); } @Override public Optional<LotteryTicketId> save(LotteryTicket ticket) { var ticketId = getNextId(); var doc = new Document(TICKET_ID, ticketId); doc.put("email", ticket.getPlayerDetails().getEmail()); doc.put("bank", ticket.getPlayerDetails().getBankAccount()); doc.put("phone", ticket.getPlayerDetails().getPhoneNumber()); doc.put("numbers", ticket.getLotteryNumbers().getNumbersAsString()); ticketsCollection.insertOne(doc); return Optional.of(new LotteryTicketId(ticketId)); } @Override public Map<LotteryTicketId, LotteryTicket> findAll() { return ticketsCollection .find(new Document()) .into(new ArrayList<>()) .stream() .map(this::docToTicket) .collect(Collectors.toMap(LotteryTicket::getId, Function.identity())); } @Override public void deleteAll() { ticketsCollection.deleteMany(new Document()); } private LotteryTicket docToTicket(Document doc) { var playerDetails = new PlayerDetails(doc.getString("email"), doc.getString("bank"), doc.getString("phone")); var numbers = Arrays.stream(doc.getString("numbers").split(",")) .map(Integer::parseInt) .collect(Collectors.toSet()); var lotteryNumbers = LotteryNumbers.create(numbers); var ticketId = new LotteryTicketId(doc.getInteger(TICKET_ID)); return new LotteryTicket(ticketId, playerDetails, lotteryNumbers); } }
var find = new Document("_id", TICKET_ID); var increase = new Document("seq", 1); var update = new Document("$inc", increase); var result = countersCollection.findOneAndUpdate(find, update); return result.getInteger("seq");
1,183
74
1,257
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java
LotteryAdministration
performLottery
class LotteryAdministration { private final LotteryTicketRepository repository; private final LotteryEventLog notifications; private final WireTransfers wireTransfers; /** * Constructor. */ @Inject public LotteryAdministration(LotteryTicketRepository repository, LotteryEventLog notifications, WireTransfers wireTransfers) { this.repository = repository; this.notifications = notifications; this.wireTransfers = wireTransfers; } /** * Get all the lottery tickets submitted for lottery. */ public Map<LotteryTicketId, LotteryTicket> getAllSubmittedTickets() { return repository.findAll(); } /** * Draw lottery numbers. */ public LotteryNumbers performLottery() {<FILL_FUNCTION_BODY>} /** * Begin new lottery round. */ public void resetLottery() { repository.deleteAll(); } }
var numbers = LotteryNumbers.createRandom(); var tickets = getAllSubmittedTickets(); for (var id : tickets.keySet()) { var lotteryTicket = tickets.get(id); var playerDetails = lotteryTicket.getPlayerDetails(); var playerAccount = playerDetails.getBankAccount(); var result = LotteryUtils.checkTicketForPrize(repository, id, numbers).getResult(); if (result == LotteryTicketCheckResult.CheckResult.WIN_PRIZE) { if (wireTransfers.transferFunds(PRIZE_AMOUNT, SERVICE_BANK_ACCOUNT, playerAccount)) { notifications.ticketWon(playerDetails, PRIZE_AMOUNT); } else { notifications.prizeError(playerDetails, PRIZE_AMOUNT); } } else if (result == LotteryTicketCheckResult.CheckResult.NO_PRIZE) { notifications.ticketDidNotWin(playerDetails); } } return numbers;
267
266
533
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java
LotteryNumbers
generateRandomNumbers
class LotteryNumbers { private final Set<Integer> numbers; public static final int MIN_NUMBER = 1; public static final int MAX_NUMBER = 20; public static final int NUM_NUMBERS = 4; /** * Constructor. Creates random lottery numbers. */ private LotteryNumbers() { numbers = new HashSet<>(); generateRandomNumbers(); } /** * Constructor. Uses given numbers. */ private LotteryNumbers(Set<Integer> givenNumbers) { numbers = new HashSet<>(); numbers.addAll(givenNumbers); } /** * Creates a random lottery number. * * @return random LotteryNumbers */ public static LotteryNumbers createRandom() { return new LotteryNumbers(); } /** * Creates lottery number from given set of numbers. * * @return given LotteryNumbers */ public static LotteryNumbers create(Set<Integer> givenNumbers) { return new LotteryNumbers(givenNumbers); } /** * Get numbers. * * @return lottery numbers */ public Set<Integer> getNumbers() { return Collections.unmodifiableSet(numbers); } /** * Get numbers as string. * * @return numbers as comma separated string */ public String getNumbersAsString() { return Joiner.on(',').join(numbers); } /** * Generates 4 unique random numbers between 1-20 into numbers set. */ private void generateRandomNumbers() {<FILL_FUNCTION_BODY>} /** * Helper class for generating random numbers. */ private static class RandomNumberGenerator { private final PrimitiveIterator.OfInt randomIterator; /** * Initialize a new random number generator that generates random numbers in the range [min, * max]. * * @param min the min value (inclusive) * @param max the max value (inclusive) */ public RandomNumberGenerator(int min, int max) { randomIterator = new SecureRandom().ints(min, max + 1).iterator(); } /** * Gets next random integer in [min, max] range. * * @return a random number in the range (min, max) */ public int nextInt() { return randomIterator.nextInt(); } } }
numbers.clear(); var generator = new RandomNumberGenerator(MIN_NUMBER, MAX_NUMBER); while (numbers.size() < NUM_NUMBERS) { var num = generator.nextInt(); numbers.add(num); }
656
68
724
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java
LotteryService
submitTicket
class LotteryService { private final LotteryTicketRepository repository; private final LotteryEventLog notifications; private final WireTransfers wireTransfers; /** * Constructor. */ @Inject public LotteryService(LotteryTicketRepository repository, LotteryEventLog notifications, WireTransfers wireTransfers) { this.repository = repository; this.notifications = notifications; this.wireTransfers = wireTransfers; } /** * Submit lottery ticket to participate in the lottery. */ public Optional<LotteryTicketId> submitTicket(LotteryTicket ticket) {<FILL_FUNCTION_BODY>} /** * Check if lottery ticket has won. */ public LotteryTicketCheckResult checkTicketForPrize( LotteryTicketId id, LotteryNumbers winningNumbers ) { return LotteryUtils.checkTicketForPrize(repository, id, winningNumbers); } }
var playerDetails = ticket.getPlayerDetails(); var playerAccount = playerDetails.getBankAccount(); var result = wireTransfers.transferFunds(TICKET_PRIZE, playerAccount, SERVICE_BANK_ACCOUNT); if (!result) { notifications.ticketSubmitError(playerDetails); return Optional.empty(); } var optional = repository.save(ticket); if (optional.isPresent()) { notifications.ticketSubmitted(playerDetails); } return optional;
271
138
409
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java
LotteryTicket
hashCode
class LotteryTicket { private final LotteryTicketId id; private final PlayerDetails playerDetails; private final LotteryNumbers lotteryNumbers; @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } var other = (LotteryTicket) obj; if (lotteryNumbers == null) { if (other.lotteryNumbers != null) { return false; } } else if (!lotteryNumbers.equals(other.lotteryNumbers)) { return false; } if (playerDetails == null) { return other.playerDetails == null; } else { return playerDetails.equals(other.playerDetails); } } }
final var prime = 31; var result = 1; result = prime * result + ((lotteryNumbers == null) ? 0 : lotteryNumbers.hashCode()); result = prime * result + ((playerDetails == null) ? 0 : playerDetails.hashCode()); return result;
263
76
339
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java
LotteryUtils
checkTicketForPrize
class LotteryUtils { private LotteryUtils() { } /** * Checks if lottery ticket has won. */ public static LotteryTicketCheckResult checkTicketForPrize( LotteryTicketRepository repository, LotteryTicketId id, LotteryNumbers winningNumbers ) {<FILL_FUNCTION_BODY>} }
var optional = repository.findById(id); if (optional.isPresent()) { if (optional.get().getLotteryNumbers().equals(winningNumbers)) { return new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 1000); } else { return new LotteryTicketCheckResult(CheckResult.NO_PRIZE); } } else { return new LotteryTicketCheckResult(CheckResult.TICKET_NOT_SUBMITTED); }
100
135
235
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java
MongoEventLog
ticketSubmitted
class MongoEventLog implements LotteryEventLog { private static final String DEFAULT_DB = "lotteryDB"; private static final String DEFAULT_EVENTS_COLLECTION = "events"; private static final String EMAIL = "email"; private static final String PHONE = "phone"; public static final String MESSAGE = "message"; private MongoClient mongoClient; private MongoDatabase database; private MongoCollection<Document> eventsCollection; private final StdOutEventLog stdOutEventLog = new StdOutEventLog(); /** * Constructor. */ public MongoEventLog() { connect(); } /** * Constructor accepting parameters. */ public MongoEventLog(String dbName, String eventsCollectionName) { connect(dbName, eventsCollectionName); } /** * Connect to database with default parameters. */ public void connect() { connect(DEFAULT_DB, DEFAULT_EVENTS_COLLECTION); } /** * Connect to database with given parameters. */ public void connect(String dbName, String eventsCollectionName) { if (mongoClient != null) { mongoClient.close(); } mongoClient = new MongoClient(System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); database = mongoClient.getDatabase(dbName); eventsCollection = database.getCollection(eventsCollectionName); } /** * Get mongo client. * * @return mongo client */ public MongoClient getMongoClient() { return mongoClient; } /** * Get mongo database. * * @return mongo database */ public MongoDatabase getMongoDatabase() { return database; } /** * Get events collection. * * @return events collection */ public MongoCollection<Document> getEventsCollection() { return eventsCollection; } @Override public void ticketSubmitted(PlayerDetails details) {<FILL_FUNCTION_BODY>} @Override public void ticketSubmitError(PlayerDetails details) { var document = new Document(EMAIL, details.getEmail()); document.put(PHONE, details.getPhoneNumber()); document.put("bank", details.getBankAccount()); document.put(MESSAGE, "Lottery ticket could not be submitted because lack of funds."); eventsCollection.insertOne(document); stdOutEventLog.ticketSubmitError(details); } @Override public void ticketDidNotWin(PlayerDetails details) { var document = new Document(EMAIL, details.getEmail()); document.put(PHONE, details.getPhoneNumber()); document.put("bank", details.getBankAccount()); document.put(MESSAGE, "Lottery ticket was checked and unfortunately did not win this time."); eventsCollection.insertOne(document); stdOutEventLog.ticketDidNotWin(details); } @Override public void ticketWon(PlayerDetails details, int prizeAmount) { var document = new Document(EMAIL, details.getEmail()); document.put(PHONE, details.getPhoneNumber()); document.put("bank", details.getBankAccount()); document.put(MESSAGE, String .format("Lottery ticket won! The bank account was deposited with %d credits.", prizeAmount)); eventsCollection.insertOne(document); stdOutEventLog.ticketWon(details, prizeAmount); } @Override public void prizeError(PlayerDetails details, int prizeAmount) { var document = new Document(EMAIL, details.getEmail()); document.put(PHONE, details.getPhoneNumber()); document.put("bank", details.getBankAccount()); document.put(MESSAGE, String .format("Lottery ticket won! Unfortunately the bank credit transfer of %d failed.", prizeAmount)); eventsCollection.insertOne(document); stdOutEventLog.prizeError(details, prizeAmount); } }
var document = new Document(EMAIL, details.getEmail()); document.put(PHONE, details.getPhoneNumber()); document.put("bank", details.getBankAccount()); document .put(MESSAGE, "Lottery ticket was submitted and bank account was charged for 3 credits."); eventsCollection.insertOne(document); stdOutEventLog.ticketSubmitted(details);
1,065
103
1,168
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java
StdOutEventLog
prizeError
class StdOutEventLog implements LotteryEventLog { @Override public void ticketSubmitted(PlayerDetails details) { LOGGER.info("Lottery ticket for {} was submitted. Bank account {} was charged for 3 credits.", details.getEmail(), details.getBankAccount()); } @Override public void ticketDidNotWin(PlayerDetails details) { LOGGER.info("Lottery ticket for {} was checked and unfortunately did not win this time.", details.getEmail()); } @Override public void ticketWon(PlayerDetails details, int prizeAmount) { LOGGER.info("Lottery ticket for {} has won! The bank account {} was deposited with {} credits.", details.getEmail(), details.getBankAccount(), prizeAmount); } @Override public void prizeError(PlayerDetails details, int prizeAmount) {<FILL_FUNCTION_BODY>} @Override public void ticketSubmitError(PlayerDetails details) { LOGGER.error("Lottery ticket for {} could not be submitted because the credit transfer" + " of 3 credits failed.", details.getEmail()); } }
LOGGER.error("Lottery ticket for {} has won! Unfortunately the bank credit transfer of" + " {} failed.", details.getEmail(), prizeAmount);
289
41
330
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java
MongoConnectionPropertiesLoader
load
class MongoConnectionPropertiesLoader { private static final String DEFAULT_HOST = "localhost"; private static final int DEFAULT_PORT = 27017; /** * Try to load connection properties from file. Fall back to default connection properties. */ public static void load() {<FILL_FUNCTION_BODY>} }
var host = DEFAULT_HOST; var port = DEFAULT_PORT; var path = System.getProperty("hexagonal.properties.path"); var properties = new Properties(); if (path != null) { try (var fin = new FileInputStream(path)) { properties.load(fin); host = properties.getProperty("mongo-host"); port = Integer.parseInt(properties.getProperty("mongo-port")); } catch (Exception e) { // error occurred, use default properties e.printStackTrace(); } } System.setProperty("mongo-host", host); System.setProperty("mongo-port", String.format("%d", port));
86
178
264
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java
SampleData
submitTickets
class SampleData { private static final List<PlayerDetails> PLAYERS; private static final SecureRandom RANDOM = new SecureRandom(); static { PLAYERS = List.of( new PlayerDetails("john@google.com", "312-342", "+3242434242"), new PlayerDetails("mary@google.com", "234-987", "+23452346"), new PlayerDetails("steve@google.com", "833-836", "+63457543"), new PlayerDetails("wayne@google.com", "319-826", "+24626"), new PlayerDetails("johnie@google.com", "983-322", "+3635635"), new PlayerDetails("andy@google.com", "934-734", "+0898245"), new PlayerDetails("richard@google.com", "536-738", "+09845325"), new PlayerDetails("kevin@google.com", "453-936", "+2423532"), new PlayerDetails("arnold@google.com", "114-988", "+5646346524"), new PlayerDetails("ian@google.com", "663-765", "+928394235"), new PlayerDetails("robin@google.com", "334-763", "+35448"), new PlayerDetails("ted@google.com", "735-964", "+98752345"), new PlayerDetails("larry@google.com", "734-853", "+043842423"), new PlayerDetails("calvin@google.com", "334-746", "+73294135"), new PlayerDetails("jacob@google.com", "444-766", "+358042354"), new PlayerDetails("edwin@google.com", "895-345", "+9752435"), new PlayerDetails("mary@google.com", "760-009", "+34203542"), new PlayerDetails("lolita@google.com", "425-907", "+9872342"), new PlayerDetails("bruno@google.com", "023-638", "+673824122"), new PlayerDetails("peter@google.com", "335-886", "+5432503945"), new PlayerDetails("warren@google.com", "225-946", "+9872341324"), new PlayerDetails("monica@google.com", "265-748", "+134124"), new PlayerDetails("ollie@google.com", "190-045", "+34453452"), new PlayerDetails("yngwie@google.com", "241-465", "+9897641231"), new PlayerDetails("lars@google.com", "746-936", "+42345298345"), new PlayerDetails("bobbie@google.com", "946-384", "+79831742"), new PlayerDetails("tyron@google.com", "310-992", "+0498837412"), new PlayerDetails("tyrell@google.com", "032-045", "+67834134"), new PlayerDetails("nadja@google.com", "000-346", "+498723"), new PlayerDetails("wendy@google.com", "994-989", "+987324454"), new PlayerDetails("luke@google.com", "546-634", "+987642435"), new PlayerDetails("bjorn@google.com", "342-874", "+7834325"), new PlayerDetails("lisa@google.com", "024-653", "+980742154"), new PlayerDetails("anton@google.com", "834-935", "+876423145"), new PlayerDetails("bruce@google.com", "284-936", "+09843212345"), new PlayerDetails("ray@google.com", "843-073", "+678324123"), new PlayerDetails("ron@google.com", "637-738", "+09842354"), new PlayerDetails("xavier@google.com", "143-947", "+375245"), new PlayerDetails("harriet@google.com", "842-404", "+131243252") ); var wireTransfers = new InMemoryBank(); PLAYERS.stream() .map(PlayerDetails::getBankAccount) .map(e -> new SimpleEntry<>(e, RANDOM.nextInt(LotteryConstants.PLAYER_MAX_BALANCE))) .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)) .forEach(wireTransfers::setFunds); } /** * Inserts lottery tickets into the database based on the sample data. */ public static void submitTickets(LotteryService lotteryService, int numTickets) {<FILL_FUNCTION_BODY>} private static PlayerDetails getRandomPlayerDetails() { return PLAYERS.get(RANDOM.nextInt(PLAYERS.size())); } }
for (var i = 0; i < numTickets; i++) { var randomPlayerDetails = getRandomPlayerDetails(); var lotteryNumbers = LotteryNumbers.createRandom(); var lotteryTicketId = new LotteryTicketId(); var ticket = new LotteryTicket(lotteryTicketId, randomPlayerDetails, lotteryNumbers); lotteryService.submitTicket(ticket); }
1,568
108
1,676
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java
ConsoleLottery
main
class ConsoleLottery { /** * Program entry point. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} private static void printMainMenu() { LOGGER.info(""); LOGGER.info("### Lottery Service Console ###"); LOGGER.info("(1) Query lottery account funds"); LOGGER.info("(2) Add funds to lottery account"); LOGGER.info("(3) Submit ticket"); LOGGER.info("(4) Check ticket"); LOGGER.info("(5) Exit"); } private static String readString(Scanner scanner) { LOGGER.info("> "); return scanner.next(); } }
MongoConnectionPropertiesLoader.load(); var injector = Guice.createInjector(new LotteryModule()); var service = injector.getInstance(LotteryService.class); var bank = injector.getInstance(WireTransfers.class); try (Scanner scanner = new Scanner(System.in)) { var exit = false; while (!exit) { printMainMenu(); var cmd = readString(scanner); var lotteryConsoleService = new LotteryConsoleServiceImpl(LOGGER); if ("1".equals(cmd)) { lotteryConsoleService.queryLotteryAccountFunds(bank, scanner); } else if ("2".equals(cmd)) { lotteryConsoleService.addFundsToLotteryAccount(bank, scanner); } else if ("3".equals(cmd)) { lotteryConsoleService.submitTicket(service, scanner); } else if ("4".equals(cmd)) { lotteryConsoleService.checkTicket(service, scanner); } else if ("5".equals(cmd)) { exit = true; } else { LOGGER.info("Unknown command"); } } }
192
302
494
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java
LotteryConsoleServiceImpl
checkTicket
class LotteryConsoleServiceImpl implements LotteryConsoleService { private final Logger logger; /** * Constructor. */ public LotteryConsoleServiceImpl(Logger logger) { this.logger = logger; } @Override public void checkTicket(LotteryService service, Scanner scanner) {<FILL_FUNCTION_BODY>} @Override public void submitTicket(LotteryService service, Scanner scanner) { logger.info("What is your email address?"); var email = readString(scanner); logger.info("What is your bank account number?"); var account = readString(scanner); logger.info("What is your phone number?"); var phone = readString(scanner); var details = new PlayerDetails(email, account, phone); logger.info("Give 4 comma separated lottery numbers?"); var numbers = readString(scanner); try { var chosen = Arrays.stream(numbers.split(",")) .map(Integer::parseInt) .collect(Collectors.toSet()); var lotteryNumbers = LotteryNumbers.create(chosen); var lotteryTicket = new LotteryTicket(new LotteryTicketId(), details, lotteryNumbers); service.submitTicket(lotteryTicket).ifPresentOrElse( (id) -> logger.info("Submitted lottery ticket with id: {}", id), () -> logger.info("Failed submitting lottery ticket - please try again.") ); } catch (Exception e) { logger.info("Failed submitting lottery ticket - please try again."); } } @Override public void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner) { logger.info("What is the account number?"); var account = readString(scanner); logger.info("How many credits do you want to deposit?"); var amount = readString(scanner); bank.setFunds(account, Integer.parseInt(amount)); logger.info("The account {} now has {} credits.", account, bank.getFunds(account)); } @Override public void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner) { logger.info("What is the account number?"); var account = readString(scanner); logger.info("The account {} has {} credits.", account, bank.getFunds(account)); } private String readString(Scanner scanner) { logger.info("> "); return scanner.next(); } }
logger.info("What is the ID of the lottery ticket?"); var id = readString(scanner); logger.info("Give the 4 comma separated winning numbers?"); var numbers = readString(scanner); try { var winningNumbers = Arrays.stream(numbers.split(",")) .map(Integer::parseInt) .limit(4) .collect(Collectors.toSet()); final var lotteryTicketId = new LotteryTicketId(Integer.parseInt(id)); final var lotteryNumbers = LotteryNumbers.create(winningNumbers); var result = service.checkTicketForPrize(lotteryTicketId, lotteryNumbers); if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.WIN_PRIZE)) { logger.info("Congratulations! The lottery ticket has won!"); } else if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.NO_PRIZE)) { logger.info("Unfortunately the lottery ticket did not win."); } else { logger.info("Such lottery ticket has not been submitted."); } } catch (Exception e) { logger.info("Failed checking the lottery ticket - please try again."); }
667
326
993
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/identity-map/src/main/java/com/iluwatar/identitymap/App.java
App
main
class App { /** * Program entry point. * * @param args command line args. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// Dummy Persons Person person1 = new Person(1, "John", 27304159); Person person2 = new Person(2, "Thomas", 42273631); Person person3 = new Person(3, "Arthur", 27489171); Person person4 = new Person(4, "Finn", 20499078); Person person5 = new Person(5, "Michael", 40599078); // Init database PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); db.insert(person1); db.insert(person2); db.insert(person3); db.insert(person4); db.insert(person5); // Init a personFinder PersonFinder finder = new PersonFinder(); finder.setDb(db); // Find persons in DataBase not the map. LOGGER.info(finder.getPerson(2).toString()); LOGGER.info(finder.getPerson(4).toString()); LOGGER.info(finder.getPerson(5).toString()); // Find the person in the map. LOGGER.info(finder.getPerson(2).toString());
56
327
383
<no_super_class>