diff --git a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java
index b8d6a41a0..0cc62c995 100644
--- a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java
+++ b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java
@@ -6,38 +6,37 @@ import java.util.concurrent.TimeUnit;
/**
*
- * Double Checked Locking is a concurrency design pattern used to reduce the overhead
- * of acquiring a lock by first testing the locking criterion (the "lock hint") without
- * actually acquiring the lock. Only if the locking criterion check indicates that
- * locking is required does the actual locking logic proceed.
+ * Double Checked Locking is a concurrency design pattern used to reduce the overhead of acquiring a
+ * lock by first testing the locking criterion (the "lock hint") without actually acquiring the
+ * lock. Only if the locking criterion check indicates that locking is required does the actual
+ * locking logic proceed.
*
- * In {@link Inventory} we store the items with a given size. However, we do not store
- * more items than the inventory size. To address concurrent access problems we
- * use double checked locking to add item to inventory. In this method, the
- * thread which gets the lock first adds the item.
+ * In {@link Inventory} we store the items with a given size. However, we do not store more items
+ * than the inventory size. To address concurrent access problems we use double checked locking to
+ * add item to inventory. In this method, the thread which gets the lock first adds the item.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- final Inventory inventory = new Inventory(1000);
- ExecutorService executorService = Executors.newFixedThreadPool(3);
- for (int i = 0; i < 3; i++) {
- executorService.execute(() -> {
- while (inventory.addItem(new Item()))
- ;
- });
- }
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ final Inventory inventory = new Inventory(1000);
+ ExecutorService executorService = Executors.newFixedThreadPool(3);
+ for (int i = 0; i < 3; i++) {
+ executorService.execute(() -> {
+ while (inventory.addItem(new Item()));
+ });
+ }
- executorService.shutdown();
- try {
- executorService.awaitTermination(5, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- System.out.println("Error waiting for ExecutorService shutdown");
- }
- }
+ executorService.shutdown();
+ try {
+ executorService.awaitTermination(5, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ System.out.println("Error waiting for ExecutorService shutdown");
+ }
+ }
}
diff --git a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java
index a58926d9d..b51e000a7 100644
--- a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java
+++ b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java
@@ -12,32 +12,30 @@ import java.util.concurrent.locks.ReentrantLock;
*/
public class Inventory {
- private final int inventorySize;
- private final List- items;
- private final Lock lock;
+ private final int inventorySize;
+ private final List
- items;
+ private final Lock lock;
- public Inventory(int inventorySize) {
- this.inventorySize = inventorySize;
- this.items = new ArrayList<>(inventorySize);
- this.lock = new ReentrantLock();
- }
-
- public boolean addItem(Item item) {
- if (items.size() < inventorySize) {
- lock.lock();
- try {
- if (items.size() < inventorySize) {
- items.add(item);
- System.out.println(Thread.currentThread()
- + ": items.size()=" + items.size()
- + ", inventorySize=" + inventorySize);
- return true;
- }
- } finally {
- lock.unlock();
- }
- }
- return false;
- }
+ public Inventory(int inventorySize) {
+ this.inventorySize = inventorySize;
+ this.items = new ArrayList<>(inventorySize);
+ this.lock = new ReentrantLock();
+ }
+ public boolean addItem(Item item) {
+ if (items.size() < inventorySize) {
+ lock.lock();
+ try {
+ if (items.size() < inventorySize) {
+ items.add(item);
+ System.out.println(Thread.currentThread() + ": items.size()=" + items.size()
+ + ", inventorySize=" + inventorySize);
+ return true;
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+ return false;
+ }
}
diff --git a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Item.java b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Item.java
index 8fc7f3888..5efe06215 100644
--- a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Item.java
+++ b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Item.java
@@ -6,7 +6,7 @@ package com.iluwatar.doublechecked.locking;
*
*/
public class Item {
-
- private String name;
- private int level;
+
+ private String name;
+ private int level;
}
diff --git a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java
index 14fd47488..bd88f223c 100644
--- a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java
+++ b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.doublechecked.locking.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java
index f32c93cb1..6514feb7f 100644
--- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java
+++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java
@@ -5,46 +5,50 @@ import java.util.List;
/**
*
- * When a message with a parameter is sent to an object, the resultant behaviour is defined by the
- * implementation of that method in the receiver. Sometimes the behaviour must also be determined
- * by the type of the parameter.
+ * When a message with a parameter is sent to an object, the resultant behaviour is defined by the
+ * implementation of that method in the receiver. Sometimes the behaviour must also be determined by
+ * the type of the parameter.
*
- * One way to implement this would be to create multiple instanceof-checks for the methods parameter.
- * However, this creates a maintenance issue. When new types are added we would also need to change
- * the method's implementation and add a new instanceof-check. This violates the single responsibility
- * principle - a class should have only one reason to change.
+ * One way to implement this would be to create multiple instanceof-checks for the methods
+ * parameter. However, this creates a maintenance issue. When new types are added we would also need
+ * to change the method's implementation and add a new instanceof-check. This violates the single
+ * responsibility principle - a class should have only one reason to change.
*
* Instead of the instanceof-checks a better way is to make another virtual call on the parameter
* object. This way new functionality can be easily added without the need to modify existing
* implementation (open-closed principle).
*
- * In this example we have hierarchy of objects ({@link GameObject}) that can collide to each other. Each
- * object has its own coordinates which are checked against the other objects' coordinates. If
+ * In this example we have hierarchy of objects ({@link GameObject}) that can collide to each other.
+ * Each object has its own coordinates which are checked against the other objects' coordinates. If
* there is an overlap, then the objects collide utilizing the Double Dispatch pattern.
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
- // initialize game objects and print their status
- List objects = new ArrayList<>();
- objects.add(new FlamingAsteroid(0, 0, 5, 5));
- objects.add(new SpaceStationMir(1, 1, 2, 2));
- objects.add(new Meteoroid(10, 10, 15, 15));
- objects.add(new SpaceStationIss(12, 12, 14, 14));
- objects.stream().forEach(o -> System.out.println(o));
- System.out.println("");
-
- // collision check
- objects.stream().forEach(o1 -> objects.stream().forEach(o2 -> { if (o1 != o2 && o1.intersectsWith(o2)) o1.collision(o2); } ));
- System.out.println("");
-
- // output eventual object statuses
- objects.stream().forEach(o -> System.out.println(o));
- System.out.println("");
- }
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ // initialize game objects and print their status
+ List objects = new ArrayList<>();
+ objects.add(new FlamingAsteroid(0, 0, 5, 5));
+ objects.add(new SpaceStationMir(1, 1, 2, 2));
+ objects.add(new Meteoroid(10, 10, 15, 15));
+ objects.add(new SpaceStationIss(12, 12, 14, 14));
+ objects.stream().forEach(o -> System.out.println(o));
+ System.out.println("");
+
+ // collision check
+ objects.stream().forEach(o1 -> objects.stream().forEach(o2 -> {
+ if (o1 != o2 && o1.intersectsWith(o2))
+ o1.collision(o2);
+ }));
+ System.out.println("");
+
+ // output eventual object statuses
+ objects.stream().forEach(o -> System.out.println(o));
+ System.out.println("");
+ }
}
diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java
index 73b633e5b..e23169897 100644
--- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java
+++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java
@@ -7,13 +7,13 @@ package com.iluwatar.doubledispatch;
*/
public class FlamingAsteroid extends Meteoroid {
- public FlamingAsteroid(int left, int top, int right, int bottom) {
- super(left, top, right, bottom);
- setOnFire(true);
- }
+ public FlamingAsteroid(int left, int top, int right, int bottom) {
+ super(left, top, right, bottom);
+ setOnFire(true);
+ }
- @Override
- public void collision(GameObject gameObject) {
- gameObject.collisionResolve(this);
- }
+ @Override
+ public void collision(GameObject gameObject) {
+ gameObject.collisionResolve(this);
+ }
}
diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java
index afe05e9b2..4fdca4dac 100644
--- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java
+++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java
@@ -2,48 +2,47 @@ package com.iluwatar.doubledispatch;
/**
*
- * Game objects have coordinates and some
- * other status information.
+ * Game objects have coordinates and some other status information.
*
*/
public abstract 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() {
- return String.format("%s at %s damaged=%b onFire=%b", this.getClass().getSimpleName(),
- super.toString(), isDamaged(), isOnFire());
- }
-
- public boolean isOnFire() {
- return onFire;
- }
-
- public void setOnFire(boolean onFire) {
- this.onFire = onFire;
- }
-
- public boolean isDamaged() {
- return damaged;
- }
-
- public void setDamaged(boolean damaged) {
- this.damaged = damaged;
- }
-
- public abstract void collision(GameObject gameObject);
-
- public abstract void collisionResolve(FlamingAsteroid asteroid);
- public abstract void collisionResolve(Meteoroid meteoroid);
+ private boolean damaged;
+ private boolean onFire;
- public abstract void collisionResolve(SpaceStationMir mir);
+ public GameObject(int left, int top, int right, int bottom) {
+ super(left, top, right, bottom);
+ }
- public abstract void collisionResolve(SpaceStationIss iss);
+ @Override
+ public String toString() {
+ return String.format("%s at %s damaged=%b onFire=%b", this.getClass().getSimpleName(),
+ super.toString(), isDamaged(), isOnFire());
+ }
+
+ public boolean isOnFire() {
+ return onFire;
+ }
+
+ public void setOnFire(boolean onFire) {
+ this.onFire = onFire;
+ }
+
+ public boolean isDamaged() {
+ return damaged;
+ }
+
+ public void setDamaged(boolean damaged) {
+ this.damaged = damaged;
+ }
+
+ 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);
}
diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java
index fb59c49b4..20d985e6a 100644
--- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java
+++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java
@@ -7,32 +7,36 @@ package com.iluwatar.doubledispatch;
*/
public class Meteoroid extends GameObject {
- public Meteoroid(int left, int top, int right, int bottom) {
- super(left, top, right, bottom);
- }
+ public Meteoroid(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 collision(GameObject gameObject) {
+ gameObject.collisionResolve(this);
+ }
- @Override
- public void collisionResolve(FlamingAsteroid asteroid) {
- System.out.println(String.format("%s hits %s.", asteroid.getClass().getSimpleName(), this.getClass().getSimpleName()));
- }
+ @Override
+ public void collisionResolve(FlamingAsteroid asteroid) {
+ System.out.println(String.format("%s hits %s.", asteroid.getClass().getSimpleName(), this
+ .getClass().getSimpleName()));
+ }
- @Override
- public void collisionResolve(Meteoroid meteoroid) {
- System.out.println(String.format("%s hits %s.", meteoroid.getClass().getSimpleName(), this.getClass().getSimpleName()));
- }
+ @Override
+ public void collisionResolve(Meteoroid meteoroid) {
+ System.out.println(String.format("%s hits %s.", meteoroid.getClass().getSimpleName(), this
+ .getClass().getSimpleName()));
+ }
- @Override
- public void collisionResolve(SpaceStationMir mir) {
- System.out.println(String.format("%s hits %s.", mir.getClass().getSimpleName(), this.getClass().getSimpleName()));
- }
+ @Override
+ public void collisionResolve(SpaceStationMir mir) {
+ System.out.println(String.format("%s hits %s.", mir.getClass().getSimpleName(), this.getClass()
+ .getSimpleName()));
+ }
- @Override
- public void collisionResolve(SpaceStationIss iss) {
- System.out.println(String.format("%s hits %s.", iss.getClass().getSimpleName(), this.getClass().getSimpleName()));
- }
+ @Override
+ public void collisionResolve(SpaceStationIss iss) {
+ System.out.println(String.format("%s hits %s.", iss.getClass().getSimpleName(), this.getClass()
+ .getSimpleName()));
+ }
}
diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java
index 12aca0056..db26265cc 100644
--- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java
+++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java
@@ -2,43 +2,46 @@ package com.iluwatar.doubledispatch;
/**
*
- * Rectangle has coordinates and can be checked for overlap against
- * other Rectangles.
+ * Rectangle has coordinates and can be checked for overlap against other Rectangles.
*
*/
public class Rectangle {
- private int left;
- private int top;
- private int right;
- private int bottom;
+ private int left;
+ private int top;
+ private int right;
+ private int bottom;
- public Rectangle(int left, int top, int right, int bottom) {
- this.left = left;
- this.top = top;
- this.right = right;
- this.bottom = bottom;
- }
-
- public int getLeft() {
- return left;
- }
- public int getTop() {
- return top;
- }
- public int getRight() {
- return right;
- }
- public int getBottom() {
- return bottom;
- }
-
- boolean intersectsWith(Rectangle r) {
- return !(r.getLeft() > getRight() || r.getRight() < getLeft() || r.getTop() > getBottom() || r.getBottom() < getTop());
- }
-
- @Override
- public String toString() {
- return String.format("[%d,%d,%d,%d]", getLeft(), getTop(), getRight(), getBottom());
- }
+ public Rectangle(int left, int top, int right, int bottom) {
+ this.left = left;
+ this.top = top;
+ this.right = right;
+ this.bottom = bottom;
+ }
+
+ public int getLeft() {
+ return left;
+ }
+
+ public int getTop() {
+ return top;
+ }
+
+ public int getRight() {
+ return right;
+ }
+
+ public int getBottom() {
+ return bottom;
+ }
+
+ boolean intersectsWith(Rectangle r) {
+ return !(r.getLeft() > getRight() || r.getRight() < getLeft() || r.getTop() > getBottom() || r
+ .getBottom() < getTop());
+ }
+
+ @Override
+ public String toString() {
+ return String.format("[%d,%d,%d,%d]", getLeft(), getTop(), getRight(), getBottom());
+ }
}
diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java
index 50eae3df8..4563b8de3 100644
--- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java
+++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java
@@ -7,12 +7,12 @@ package com.iluwatar.doubledispatch;
*/
public class SpaceStationIss extends SpaceStationMir {
- public SpaceStationIss(int left, int top, int right, int bottom) {
- super(left, top, right, bottom);
- }
+ public SpaceStationIss(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 collision(GameObject gameObject) {
+ gameObject.collisionResolve(this);
+ }
}
diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java
index 059b41271..5a4a19aaa 100644
--- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java
+++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java
@@ -7,45 +7,42 @@ package com.iluwatar.doubledispatch;
*/
public class SpaceStationMir extends GameObject {
- public SpaceStationMir(int left, int top, int right, int bottom) {
- super(left, top, right, bottom);
- }
+ 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 collision(GameObject gameObject) {
+ gameObject.collisionResolve(this);
+ }
- @Override
- public void collisionResolve(FlamingAsteroid asteroid) {
- System.out.println(String.format("%s hits %s. %s is damaged! %s is set on fire!",
- asteroid.getClass().getSimpleName(), this.getClass().getSimpleName(),
- this.getClass().getSimpleName(), this.getClass().getSimpleName()));
- setDamaged(true);
- setOnFire(true);
- }
+ @Override
+ public void collisionResolve(FlamingAsteroid asteroid) {
+ System.out.println(String.format("%s hits %s. %s is damaged! %s 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) {
- System.out.println(String.format("%s hits %s. %s is damaged!",
- meteoroid.getClass().getSimpleName(), this.getClass().getSimpleName(),
- this.getClass().getSimpleName()));
- setDamaged(true);
- }
+ @Override
+ public void collisionResolve(Meteoroid meteoroid) {
+ System.out.println(String.format("%s hits %s. %s is damaged!", meteoroid.getClass()
+ .getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName()));
+ setDamaged(true);
+ }
- @Override
- public void collisionResolve(SpaceStationMir mir) {
- System.out.println(String.format("%s hits %s. %s is damaged!",
- mir.getClass().getSimpleName(), this.getClass().getSimpleName(),
- this.getClass().getSimpleName()));
- setDamaged(true);
- }
+ @Override
+ public void collisionResolve(SpaceStationMir mir) {
+ System.out.println(String.format("%s hits %s. %s is damaged!", mir.getClass().getSimpleName(),
+ this.getClass().getSimpleName(), this.getClass().getSimpleName()));
+ setDamaged(true);
+ }
- @Override
- public void collisionResolve(SpaceStationIss iss) {
- System.out.println(String.format("%s hits %s. %s is damaged!",
- iss.getClass().getSimpleName(), this.getClass().getSimpleName(),
- this.getClass().getSimpleName()));
- setDamaged(true);
- }
+ @Override
+ public void collisionResolve(SpaceStationIss iss) {
+ System.out.println(String.format("%s hits %s. %s is damaged!", iss.getClass().getSimpleName(),
+ this.getClass().getSimpleName(), this.getClass().getSimpleName()));
+ setDamaged(true);
+ }
}
diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java
index be93ee559..c5cd213b5 100644
--- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java
+++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java
@@ -10,10 +10,10 @@ import com.iluwatar.doubledispatch.App;
*
*/
public class AppTest {
-
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java
index bb8aa954e..fad10c490 100644
--- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java
+++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java
@@ -12,11 +12,11 @@ import com.iluwatar.doubledispatch.Rectangle;
*/
public class RectangleTest {
- @Test
- public void test() {
- Assert.assertTrue(new Rectangle(0,0,1,1).intersectsWith(new Rectangle(0,0,1,1)));
- Assert.assertTrue(new Rectangle(0,0,1,1).intersectsWith(new Rectangle(-1,-5,7,8)));
- Assert.assertFalse(new Rectangle(0,0,1,1).intersectsWith(new Rectangle(2,2,3,3)));
- Assert.assertFalse(new Rectangle(0,0,1,1).intersectsWith(new Rectangle(-2,-2,-1,-1)));
- }
+ @Test
+ public void test() {
+ Assert.assertTrue(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(0, 0, 1, 1)));
+ Assert.assertTrue(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(-1, -5, 7, 8)));
+ Assert.assertFalse(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(2, 2, 3, 3)));
+ Assert.assertFalse(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(-2, -2, -1, -1)));
+ }
}
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java
index b69d8ceaa..a16c36444 100644
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java
+++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java
@@ -5,39 +5,40 @@ import java.util.List;
/**
*
- * A system with lots of objects can lead to complexities when a client wants to subscribe
- * to events. The client has to find and register for each object individually, if each
- * object has multiple events then each event requires a separate subscription.
+ * A system with lots of objects can lead to complexities when a client wants to subscribe to
+ * events. The client has to find and register for each object individually, if each object has
+ * multiple events then each event requires a separate subscription.
*
- * An Event Aggregator acts as a single source of events for many objects. It registers
- * for all the events of the many objects allowing clients to register with just the aggregator.
+ * An Event Aggregator acts as a single source of events for many objects. It registers for all the
+ * events of the many objects allowing clients to register with just the aggregator.
*
* In the example {@link LordBaelish}, {@link LordVarys} and {@link Scout} deliver events to
- * {@link KingsHand}. {@link KingsHand}, the event aggregator, then delivers the events
- * to {@link KingJoffrey}.
+ * {@link KingsHand}. {@link KingsHand}, the event aggregator, then delivers the events to
+ * {@link KingJoffrey}.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
-
- KingJoffrey kingJoffrey = new KingJoffrey();
- KingsHand kingsHand = new KingsHand(kingJoffrey);
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
- List emitters = new ArrayList<>();
- emitters.add(kingsHand);
- emitters.add(new LordBaelish(kingsHand));
- emitters.add(new LordVarys(kingsHand));
- emitters.add(new Scout(kingsHand));
-
- for (Weekday day: Weekday.values()) {
- for (EventEmitter emitter: emitters) {
- emitter.timePasses(day);
- }
- }
- }
+ KingJoffrey kingJoffrey = new KingJoffrey();
+ KingsHand kingsHand = new KingsHand(kingJoffrey);
+
+ List emitters = new ArrayList<>();
+ emitters.add(kingsHand);
+ emitters.add(new LordBaelish(kingsHand));
+ emitters.add(new LordVarys(kingsHand));
+ emitters.add(new Scout(kingsHand));
+
+ for (Weekday day : Weekday.values()) {
+ for (EventEmitter emitter : emitters) {
+ emitter.timePasses(day);
+ }
+ }
+ }
}
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java
index 79d496b80..ab66a6612 100644
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java
+++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java
@@ -7,15 +7,16 @@ package com.iluwatar.event.aggregator;
*/
public enum Event {
- STARK_SIGHTED("Stark sighted"), WARSHIPS_APPROACHING("Warships approaching"), TRAITOR_DETECTED("Traitor detected");
-
- private String description;
-
- Event(String description) {
- this.description = description;
- }
-
- public String toString() {
- return description;
- }
+ STARK_SIGHTED("Stark sighted"), WARSHIPS_APPROACHING("Warships approaching"), TRAITOR_DETECTED(
+ "Traitor detected");
+
+ private String description;
+
+ Event(String description) {
+ this.description = description;
+ }
+
+ public String toString() {
+ return description;
+ }
}
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java
index 1832afeaa..a55d7d0e8 100644
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java
+++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java
@@ -10,26 +10,26 @@ import java.util.List;
*/
public abstract class EventEmitter {
- private List observers;
+ private List observers;
- public EventEmitter() {
- observers = new LinkedList<>();
- }
+ public EventEmitter() {
+ observers = new LinkedList<>();
+ }
- public EventEmitter(EventObserver obs) {
- this();
- registerObserver(obs);
- }
-
- public void registerObserver(EventObserver obs) {
- observers.add(obs);
- }
-
- protected void notifyObservers(Event e) {
- for (EventObserver obs: observers) {
- obs.onEvent(e);
- }
- }
-
- public abstract void timePasses(Weekday day);
+ public EventEmitter(EventObserver obs) {
+ this();
+ registerObserver(obs);
+ }
+
+ public void registerObserver(EventObserver obs) {
+ observers.add(obs);
+ }
+
+ protected void notifyObservers(Event e) {
+ for (EventObserver obs : observers) {
+ obs.onEvent(e);
+ }
+ }
+
+ public abstract void timePasses(Weekday day);
}
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java
index a9785627f..dcc5ccab6 100644
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java
+++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java
@@ -6,7 +6,7 @@ package com.iluwatar.event.aggregator;
*
*/
public interface EventObserver {
-
- void onEvent(Event e);
+
+ void onEvent(Event e);
}
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java
index da45f2f1e..d6cb252cd 100644
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java
+++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java
@@ -7,8 +7,8 @@ package com.iluwatar.event.aggregator;
*/
public class KingJoffrey implements EventObserver {
- @Override
- public void onEvent(Event e) {
- System.out.println("Received event from the King's Hand: " + e.toString());
- }
+ @Override
+ public void onEvent(Event e) {
+ System.out.println("Received event from the King's Hand: " + e.toString());
+ }
}
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java
index a3e01334b..368033810 100644
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java
+++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java
@@ -2,27 +2,26 @@ package com.iluwatar.event.aggregator;
/**
*
- * KingsHand observes events from multiple sources and delivers them
- * to listeners.
+ * KingsHand observes events from multiple sources and delivers them to listeners.
*
*/
public class KingsHand extends EventEmitter implements EventObserver {
- public KingsHand() {
- super();
- }
+ public KingsHand() {
+ super();
+ }
- public KingsHand(EventObserver obs) {
- super(obs);
- }
-
- @Override
- public void onEvent(Event e) {
- notifyObservers(e);
- }
+ public KingsHand(EventObserver obs) {
+ super(obs);
+ }
- @Override
- public void timePasses(Weekday day) {
- // NOP
- }
+ @Override
+ public void onEvent(Event e) {
+ notifyObservers(e);
+ }
+
+ @Override
+ public void timePasses(Weekday day) {
+ // NOP
+ }
}
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java
index b13ec88fc..6fafceb02 100644
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java
+++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java
@@ -6,19 +6,19 @@ package com.iluwatar.event.aggregator;
*
*/
public class LordBaelish extends EventEmitter {
-
- public LordBaelish() {
- super();
- }
- public LordBaelish(EventObserver obs) {
- super(obs);
- }
-
- @Override
- public void timePasses(Weekday day) {
- if (day.equals(Weekday.FRIDAY)) {
- notifyObservers(Event.STARK_SIGHTED);
- }
- }
+ public LordBaelish() {
+ super();
+ }
+
+ public LordBaelish(EventObserver obs) {
+ super(obs);
+ }
+
+ @Override
+ public void timePasses(Weekday day) {
+ if (day.equals(Weekday.FRIDAY)) {
+ notifyObservers(Event.STARK_SIGHTED);
+ }
+ }
}
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java
index d1fec048a..880cf4e85 100644
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java
+++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java
@@ -6,19 +6,19 @@ package com.iluwatar.event.aggregator;
*
*/
public class LordVarys extends EventEmitter {
-
- public LordVarys() {
- super();
- }
- public LordVarys(EventObserver obs) {
- super(obs);
- }
-
- @Override
- public void timePasses(Weekday day) {
- if (day.equals(Weekday.SATURDAY)) {
- notifyObservers(Event.TRAITOR_DETECTED);
- }
- }
+ public LordVarys() {
+ super();
+ }
+
+ public LordVarys(EventObserver obs) {
+ super(obs);
+ }
+
+ @Override
+ public void timePasses(Weekday day) {
+ if (day.equals(Weekday.SATURDAY)) {
+ notifyObservers(Event.TRAITOR_DETECTED);
+ }
+ }
}
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java
index 8ff4e04ab..7eb6878ae 100644
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java
+++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java
@@ -6,19 +6,19 @@ package com.iluwatar.event.aggregator;
*
*/
public class Scout extends EventEmitter {
-
- public Scout() {
- super();
- }
- public Scout(EventObserver obs) {
- super(obs);
- }
-
- @Override
- public void timePasses(Weekday day) {
- if (day.equals(Weekday.TUESDAY)) {
- notifyObservers(Event.WARSHIPS_APPROACHING);
- }
- }
+ public Scout() {
+ super();
+ }
+
+ public Scout(EventObserver obs) {
+ super(obs);
+ }
+
+ @Override
+ public void timePasses(Weekday day) {
+ if (day.equals(Weekday.TUESDAY)) {
+ notifyObservers(Event.WARSHIPS_APPROACHING);
+ }
+ }
}
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java
index bafc4f36a..24cc02a25 100644
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java
+++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java
@@ -6,16 +6,17 @@ package com.iluwatar.event.aggregator;
*
*/
public enum Weekday {
-
- MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY("Saturday"), SUNDAY("Sunday");
- private String description;
-
- Weekday(String description) {
- this.description = description;
- }
-
- public String toString() {
- return description;
- }
+ MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY(
+ "Friday"), SATURDAY("Saturday"), SUNDAY("Sunday");
+
+ private String description;
+
+ Weekday(String description) {
+ this.description = description;
+ }
+
+ public String toString() {
+ return description;
+ }
}
diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java
index f8f765880..0cb76c215 100644
--- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java
+++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java
@@ -1,4 +1,5 @@
package com.iluwatar.event.aggregator;
+
import org.junit.Test;
import com.iluwatar.event.aggregator.App;
@@ -10,9 +11,9 @@ import com.iluwatar.event.aggregator.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/App.java b/execute-around/src/main/java/com/iluwatar/execute/around/App.java
index 910a024de..4a0648dbe 100644
--- a/execute-around/src/main/java/com/iluwatar/execute/around/App.java
+++ b/execute-around/src/main/java/com/iluwatar/execute/around/App.java
@@ -4,32 +4,33 @@ import java.io.FileWriter;
import java.io.IOException;
/**
- * The Execute Around idiom specifies some code to be executed before and after
- * a method. Typically the idiom is used when the API has methods to be executed in
- * pairs, such as resource allocation/deallocation or lock acquisition/release.
+ * The Execute Around idiom specifies some code to be executed before and after a method. Typically
+ * the idiom is used when the API has methods to be executed in pairs, such as resource
+ * allocation/deallocation or lock acquisition/release.
*
- * In this example, we have {@link SimpleFileWriter} class that opens and closes the file
- * for the user. The user specifies only what to do with the file by providing the
- * {@link FileWriterAction} implementation.
+ * In this example, we have {@link SimpleFileWriter} class that opens and closes the file for the
+ * user. The user specifies only what to do with the file by providing the {@link FileWriterAction}
+ * implementation.
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- * @throws IOException
- */
- public static void main( String[] args ) throws IOException {
- new SimpleFileWriter("testfile.txt", new FileWriterAction() {
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ * @throws IOException
+ */
+ public static void main(String[] args) throws IOException {
- @Override
- public void writeFile(FileWriter writer) throws IOException {
- writer.write("Hello");
- writer.append(" ");
- writer.append("there!");
- }
- });
- }
+ new SimpleFileWriter("testfile.txt", new FileWriterAction() {
+
+ @Override
+ public void writeFile(FileWriter writer) throws IOException {
+ writer.write("Hello");
+ writer.append(" ");
+ writer.append("there!");
+ }
+ });
+ }
}
diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java b/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java
index 904600ec6..1477c0ae4 100644
--- a/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java
+++ b/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java
@@ -10,6 +10,6 @@ import java.io.IOException;
*/
public interface FileWriterAction {
- void writeFile(FileWriter writer) throws IOException;
-
+ void writeFile(FileWriter writer) throws IOException;
+
}
diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java b/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java
index a7ee11d15..be89ff9ce 100644
--- a/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java
+++ b/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java
@@ -5,19 +5,18 @@ import java.io.IOException;
/**
*
- * SimpleFileWriter handles opening and closing file for the user. The user
- * only has to specify what to do with the file resource through {@link FileWriterAction}
- * parameter.
+ * SimpleFileWriter handles opening and closing file for the user. The user only has to specify what
+ * to do with the file resource through {@link FileWriterAction} parameter.
*
*/
public class SimpleFileWriter {
- public SimpleFileWriter(String filename, FileWriterAction action) throws IOException {
- FileWriter writer = new FileWriter(filename);
- try {
- action.writeFile(writer);
- } finally {
- writer.close();
- }
- }
+ public SimpleFileWriter(String filename, FileWriterAction action) throws IOException {
+ FileWriter writer = new FileWriter(filename);
+ try {
+ action.writeFile(writer);
+ } finally {
+ writer.close();
+ }
+ }
}
diff --git a/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java b/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java
index 1e8a45947..9eb3dbf5f 100644
--- a/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java
+++ b/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java
@@ -15,17 +15,17 @@ import com.iluwatar.execute.around.App;
*
*/
public class AppTest {
-
- @Test
- public void test() throws IOException {
- String[] args = {};
- App.main(args);
- }
-
- @Before
- @After
- public void cleanup() {
- File file = new File("testfile.txt");
- file.delete();
- }
+
+ @Test
+ public void test() throws IOException {
+ String[] args = {};
+ App.main(args);
+ }
+
+ @Before
+ @After
+ public void cleanup() {
+ File file = new File("testfile.txt");
+ file.delete();
+ }
}
diff --git a/facade/src/main/java/com/iluwatar/facade/App.java b/facade/src/main/java/com/iluwatar/facade/App.java
index 37cda0281..bcc492e0b 100644
--- a/facade/src/main/java/com/iluwatar/facade/App.java
+++ b/facade/src/main/java/com/iluwatar/facade/App.java
@@ -2,27 +2,28 @@ package com.iluwatar.facade;
/**
*
- * The Facade design pattern is often used when a system is very complex or difficult
- * to understand because the system has a large number of interdependent classes or
- * its source code is unavailable. This pattern hides the complexities of the larger
- * system and provides a simpler interface to the client. It typically involves a single
- * wrapper class which contains a set of members required by client. These members access
- * the system on behalf of the facade client and hide the implementation details.
+ * The Facade design pattern is often used when a system is very complex or difficult to understand
+ * because the system has a large number of interdependent classes or its source code is
+ * unavailable. This pattern hides the complexities of the larger system and provides a simpler
+ * interface to the client. It typically involves a single wrapper class which contains a set of
+ * members required by client. These members access the system on behalf of the facade client and
+ * hide the implementation details.
*
- * In this example the Facade is ({@link DwarvenGoldmineFacade}) and it provides a simpler
- * interface to the goldmine subsystem.
+ * In this example the Facade is ({@link DwarvenGoldmineFacade}) and it provides a simpler interface
+ * to the goldmine subsystem.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade();
- facade.startNewDay();
- facade.digOutGold();
- facade.endDay();
- }
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade();
+ facade.startNewDay();
+ facade.digOutGold();
+ facade.endDay();
+ }
}
diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java b/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java
index 7c33fd267..d2b6f366e 100644
--- a/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java
+++ b/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java
@@ -7,14 +7,13 @@ package com.iluwatar.facade;
*/
public class DwarvenCartOperator extends DwarvenMineWorker {
- @Override
- public void work() {
- System.out.println(name() + " moves gold chunks out of the mine.");
- }
-
- @Override
- public String name() {
- return "Dwarf cart operator";
- }
+ @Override
+ public void work() {
+ System.out.println(name() + " moves gold chunks out of the mine.");
+ }
+ @Override
+ public String name() {
+ return "Dwarf cart operator";
+ }
}
diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java
index b503889b7..df5ab1356 100644
--- a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java
+++ b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java
@@ -7,14 +7,13 @@ package com.iluwatar.facade;
*/
public class DwarvenGoldDigger extends DwarvenMineWorker {
- @Override
- public void work() {
- System.out.println(name() + " digs for gold.");
- }
-
- @Override
- public String name() {
- return "Dwarf gold digger";
- }
+ @Override
+ public void work() {
+ System.out.println(name() + " digs for gold.");
+ }
+ @Override
+ public String name() {
+ return "Dwarf gold digger";
+ }
}
diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java
index 83a989fa7..d6b653eaa 100644
--- a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java
+++ b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java
@@ -6,40 +6,39 @@ import java.util.List;
/**
*
- * DwarvenGoldmineFacade provides a single interface
- * through which users can operate the subsystems.
+ * DwarvenGoldmineFacade provides a single interface through which users can operate the subsystems.
*
- * This makes the goldmine easier to operate and
- * cuts the dependencies from the goldmine user to
- * the subsystems.
+ * This makes the goldmine easier to operate and cuts the dependencies from the goldmine user to the
+ * subsystems.
*
*/
public class DwarvenGoldmineFacade {
- private final List workers;
+ private final List workers;
- public DwarvenGoldmineFacade() {
- workers = new ArrayList<>();
- workers.add(new DwarvenGoldDigger());
- workers.add(new DwarvenCartOperator());
- workers.add(new DwarvenTunnelDigger());
- }
+ public DwarvenGoldmineFacade() {
+ workers = new ArrayList<>();
+ workers.add(new DwarvenGoldDigger());
+ workers.add(new DwarvenCartOperator());
+ workers.add(new DwarvenTunnelDigger());
+ }
- public void startNewDay() {
- makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE);
- }
+ public void startNewDay() {
+ makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE);
+ }
- public void digOutGold() {
- makeActions(workers, DwarvenMineWorker.Action.WORK);
- }
+ public void digOutGold() {
+ makeActions(workers, DwarvenMineWorker.Action.WORK);
+ }
- public void endDay() {
- makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP);
- }
+ public void endDay() {
+ makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP);
+ }
- private void makeActions(Collection workers, DwarvenMineWorker.Action... actions) {
- for (DwarvenMineWorker worker : workers) {
- worker.action(actions);
- }
+ private void makeActions(Collection workers,
+ DwarvenMineWorker.Action... actions) {
+ for (DwarvenMineWorker worker : workers) {
+ worker.action(actions);
}
+ }
}
diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java
index 3dd51f907..d329fe84b 100644
--- a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java
+++ b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java
@@ -7,56 +7,56 @@ package com.iluwatar.facade;
*/
public abstract class DwarvenMineWorker {
- public void goToSleep() {
- System.out.println(name() + " goes to sleep.");
- }
+ public void goToSleep() {
+ System.out.println(name() + " goes to sleep.");
+ }
- public void wakeUp() {
- System.out.println(name() + " wakes up.");
- }
+ public void wakeUp() {
+ System.out.println(name() + " wakes up.");
+ }
- public void goHome() {
- System.out.println(name() + " goes home.");
- }
+ public void goHome() {
+ System.out.println(name() + " goes home.");
+ }
- public void goToMine() {
- System.out.println(name() + " goes to the mine.");
- }
+ public void goToMine() {
+ System.out.println(name() + " goes to the mine.");
+ }
- private void action(Action action) {
- switch (action) {
- case GO_TO_SLEEP:
- goToSleep();
- break;
- case WAKE_UP:
- wakeUp();
- break;
- case GO_HOME:
- goHome();
- break;
- case GO_TO_MINE:
- goToMine();
- break;
- case WORK:
- work();
- break;
- default:
- System.out.println("Undefined action");
- break;
- }
+ private void action(Action action) {
+ switch (action) {
+ case GO_TO_SLEEP:
+ goToSleep();
+ break;
+ case WAKE_UP:
+ wakeUp();
+ break;
+ case GO_HOME:
+ goHome();
+ break;
+ case GO_TO_MINE:
+ goToMine();
+ break;
+ case WORK:
+ work();
+ break;
+ default:
+ System.out.println("Undefined action");
+ break;
}
+ }
- public void action(Action... actions) {
- for (Action action : actions) {
- action(action);
- }
+ public void action(Action... actions) {
+ for (Action action : actions) {
+ action(action);
}
+ }
- public abstract void work();
+ public abstract void work();
- public abstract String name();
+ public abstract String name();
- static enum Action {
- GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK
- }
+ static enum Action {
+ GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK
+ }
}
diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java b/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java
index 05fe02fb6..1d3dbe99d 100644
--- a/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java
+++ b/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java
@@ -7,14 +7,13 @@ package com.iluwatar.facade;
*/
public class DwarvenTunnelDigger extends DwarvenMineWorker {
- @Override
- public void work() {
- System.out.println(name() + " creates another promising tunnel.");
- }
-
- @Override
- public String name() {
- return "Dwarven tunnel digger";
- }
+ @Override
+ public void work() {
+ System.out.println(name() + " creates another promising tunnel.");
+ }
+ @Override
+ public String name() {
+ return "Dwarven tunnel digger";
+ }
}
diff --git a/facade/src/test/java/com/iluwatar/facade/AppTest.java b/facade/src/test/java/com/iluwatar/facade/AppTest.java
index bfca5473a..49b7c01c4 100644
--- a/facade/src/test/java/com/iluwatar/facade/AppTest.java
+++ b/facade/src/test/java/com/iluwatar/facade/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.facade.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/App.java b/factory-method/src/main/java/com/iluwatar/factory/method/App.java
index 118413564..27b7e3121 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/App.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/App.java
@@ -2,39 +2,39 @@ package com.iluwatar.factory.method;
/**
*
- * The Factory Method is a creational design pattern which uses factory methods to deal
- * with the problem of creating objects without specifying the exact class of object
- * that will be created. This is done by creating objects via calling a factory
- * method either specified in an interface and implemented by child classes, or implemented
- * in a base class and optionally overridden by derived classes—rather than by calling a
- * constructor.
+ * The Factory Method is a creational design pattern which uses factory methods to deal with the
+ * problem of creating objects without specifying the exact class of object that will be created.
+ * This is done by creating objects via calling a factory method either specified in an interface
+ * and implemented by child classes, or implemented in a base class and optionally overridden by
+ * derived classes—rather than by calling a constructor.
*
* In this Factory Method example we have an interface ({@link Blacksmith}) with a method for
- * creating objects ({@link Blacksmith#manufactureWeapon}). The concrete subclasses
- * ({@link OrcBlacksmith}, {@link ElfBlacksmith}) then override the method to produce
- * objects of their liking.
+ * creating objects ({@link Blacksmith#manufactureWeapon}). The concrete subclasses (
+ * {@link OrcBlacksmith}, {@link ElfBlacksmith}) then override the method to produce objects of
+ * their liking.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- Blacksmith blacksmith;
- Weapon weapon;
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ Blacksmith blacksmith;
+ Weapon weapon;
- blacksmith = new OrcBlacksmith();
- weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
- System.out.println(weapon);
- weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
- System.out.println(weapon);
+ blacksmith = new OrcBlacksmith();
+ weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
+ System.out.println(weapon);
+ weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
+ System.out.println(weapon);
- blacksmith = new ElfBlacksmith();
- weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
- System.out.println(weapon);
- weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
- System.out.println(weapon);
- }
+ blacksmith = new ElfBlacksmith();
+ weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
+ System.out.println(weapon);
+ weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
+ System.out.println(weapon);
+ }
}
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java
index 516c993a9..991a9d433 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java
@@ -7,6 +7,6 @@ package com.iluwatar.factory.method;
*/
public interface Blacksmith {
- Weapon manufactureWeapon(WeaponType weaponType);
+ Weapon manufactureWeapon(WeaponType weaponType);
}
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java
index 9a5e62890..99de5329b 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java
@@ -7,8 +7,8 @@ package com.iluwatar.factory.method;
*/
public class ElfBlacksmith implements Blacksmith {
- public Weapon manufactureWeapon(WeaponType weaponType) {
- return new ElfWeapon(weaponType);
- }
+ public Weapon manufactureWeapon(WeaponType weaponType) {
+ return new ElfWeapon(weaponType);
+ }
}
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java
index 75bb8a9e0..d2f38bc48 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java
@@ -7,15 +7,14 @@ package com.iluwatar.factory.method;
*/
public class ElfWeapon implements Weapon {
- private WeaponType weaponType;
+ private WeaponType weaponType;
- public ElfWeapon(WeaponType weaponType) {
- this.weaponType = weaponType;
- }
-
- @Override
- public String toString() {
- return "Elven " + weaponType;
- }
+ public ElfWeapon(WeaponType weaponType) {
+ this.weaponType = weaponType;
+ }
+ @Override
+ public String toString() {
+ return "Elven " + weaponType;
+ }
}
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java
index 382507ec9..c4db6c223 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java
@@ -7,8 +7,7 @@ package com.iluwatar.factory.method;
*/
public class OrcBlacksmith implements Blacksmith {
- public Weapon manufactureWeapon(WeaponType weaponType) {
- return new OrcWeapon(weaponType);
- }
-
+ public Weapon manufactureWeapon(WeaponType weaponType) {
+ return new OrcWeapon(weaponType);
+ }
}
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java
index 85500799e..48cd9c5a3 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java
@@ -7,15 +7,14 @@ package com.iluwatar.factory.method;
*/
public class OrcWeapon implements Weapon {
- private WeaponType weaponType;
+ private WeaponType weaponType;
- public OrcWeapon(WeaponType weaponType) {
- this.weaponType = weaponType;
- }
-
- @Override
- public String toString() {
- return "Orcish " + weaponType;
- }
+ public OrcWeapon(WeaponType weaponType) {
+ this.weaponType = weaponType;
+ }
+ @Override
+ public String toString() {
+ return "Orcish " + weaponType;
+ }
}
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java b/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java
index 1c0341670..4c8f83e9b 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java
@@ -7,16 +7,16 @@ package com.iluwatar.factory.method;
*/
public enum WeaponType {
- SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED("");
+ SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED("");
- private String title;
+ private String title;
- WeaponType(String title) {
- this.title = title;
- }
+ WeaponType(String title) {
+ this.title = title;
+ }
- @Override
- public String toString() {
- return title;
- }
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java
index c6db18b3e..cb48d9ad7 100644
--- a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java
+++ b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.factory.method.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java
index 7733df37d..bdff83e17 100644
--- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java
+++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java
@@ -11,13 +11,15 @@ import java.util.function.Predicate;
import static java.lang.String.valueOf;
/**
- * The Fluent Interface pattern is useful when you want to provide an easy readable, flowing API. Those
- * interfaces tend to mimic domain specific languages, so they can nearly be read as human languages.
+ * The Fluent Interface pattern is useful when you want to provide an easy readable, flowing API.
+ * Those interfaces tend to mimic domain specific languages, so they can nearly be read as human
+ * languages.
*
* In this example two implementations of a {@link FluentIterable} interface are given. The
- * {@link SimpleFluentIterable} evaluates eagerly and would be too costly for real world applications.
- * The {@link LazyFluentIterable} is evaluated on termination. Their usage is demonstrated with a
- * simple number list that is filtered, transformed and collected. The result is printed afterwards.
+ * {@link SimpleFluentIterable} evaluates eagerly and would be too costly for real world
+ * applications. The {@link LazyFluentIterable} is evaluated on termination. Their usage is
+ * demonstrated with a simple number list that is filtered, transformed and collected. The result is
+ * printed afterwards.
*
*/
public class App {
@@ -25,11 +27,9 @@ public class App {
public static void main(String[] args) {
List integerList = new ArrayList<>();
- integerList.addAll(Arrays.asList(
- 1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97,
- 45, 23, 2, -68, 45
- ));
-
+ integerList.addAll(Arrays.asList(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2,
+ -68, 45));
+
prettyPrint("The initial list contains: ", integerList);
List firstFiveNegatives =
diff --git a/flux/src/main/java/com/iluwatar/flux/action/Action.java b/flux/src/main/java/com/iluwatar/flux/action/Action.java
index 24d294be7..b456c1ebe 100644
--- a/flux/src/main/java/com/iluwatar/flux/action/Action.java
+++ b/flux/src/main/java/com/iluwatar/flux/action/Action.java
@@ -7,13 +7,13 @@ package com.iluwatar.flux.action;
*/
public abstract class Action {
- private ActionType type;
-
- public Action(ActionType type) {
- this.type = type;
- }
-
- public ActionType getType() {
- return type;
- }
+ private ActionType type;
+
+ public Action(ActionType type) {
+ this.type = type;
+ }
+
+ public ActionType getType() {
+ return type;
+ }
}
diff --git a/flux/src/main/java/com/iluwatar/flux/action/ActionType.java b/flux/src/main/java/com/iluwatar/flux/action/ActionType.java
index 318ca1b12..bbe13bc39 100644
--- a/flux/src/main/java/com/iluwatar/flux/action/ActionType.java
+++ b/flux/src/main/java/com/iluwatar/flux/action/ActionType.java
@@ -7,6 +7,6 @@ package com.iluwatar.flux.action;
*/
public enum ActionType {
- MENU_ITEM_SELECTED, CONTENT_CHANGED;
-
+ MENU_ITEM_SELECTED, CONTENT_CHANGED;
+
}
diff --git a/flux/src/main/java/com/iluwatar/flux/action/Content.java b/flux/src/main/java/com/iluwatar/flux/action/Content.java
index e53871d89..84910b3af 100644
--- a/flux/src/main/java/com/iluwatar/flux/action/Content.java
+++ b/flux/src/main/java/com/iluwatar/flux/action/Content.java
@@ -6,17 +6,18 @@ package com.iluwatar.flux.action;
*
*/
public enum Content {
-
- PRODUCTS("Products - This page lists the company's products."), COMPANY("Company - This page displays information about the company.");
-
- private String title;
- private Content(String title) {
- this.title = title;
- }
-
- @Override
- public String toString() {
- return title;
- }
+ PRODUCTS("Products - This page lists the company's products."), COMPANY(
+ "Company - This page displays information about the company.");
+
+ private String title;
+
+ private Content(String title) {
+ this.title = title;
+ }
+
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java b/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java
index 2c1a40e6e..842a5282f 100644
--- a/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java
+++ b/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java
@@ -7,14 +7,14 @@ package com.iluwatar.flux.action;
*/
public class ContentAction extends Action {
- private Content content;
+ private Content content;
- public ContentAction(Content content) {
- super(ActionType.CONTENT_CHANGED);
- this.content = content;
- }
-
- public Content getContent() {
- return content;
- }
+ public ContentAction(Content content) {
+ super(ActionType.CONTENT_CHANGED);
+ this.content = content;
+ }
+
+ public Content getContent() {
+ return content;
+ }
}
diff --git a/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java b/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java
index a3dd9875e..71e47e051 100644
--- a/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java
+++ b/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java
@@ -8,14 +8,14 @@ package com.iluwatar.flux.action;
*/
public class MenuAction extends Action {
- private MenuItem menuItem;
+ private MenuItem menuItem;
- public MenuAction(MenuItem menuItem) {
- super(ActionType.MENU_ITEM_SELECTED);
- this.menuItem = menuItem;
- }
-
- public MenuItem getMenuItem() {
- return menuItem;
- }
+ public MenuAction(MenuItem menuItem) {
+ super(ActionType.MENU_ITEM_SELECTED);
+ this.menuItem = menuItem;
+ }
+
+ public MenuItem getMenuItem() {
+ return menuItem;
+ }
}
diff --git a/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java b/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java
index d842fca78..c1732bb97 100644
--- a/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java
+++ b/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java
@@ -6,17 +6,17 @@ package com.iluwatar.flux.action;
*
*/
public enum MenuItem {
-
- HOME("Home"), PRODUCTS("Products"), COMPANY("Company");
-
- private String title;
- MenuItem(String title) {
- this.title = title;
- }
-
- @Override
- public String toString() {
- return title;
- }
+ HOME("Home"), PRODUCTS("Products"), COMPANY("Company");
+
+ private String title;
+
+ MenuItem(String title) {
+ this.title = title;
+ }
+
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/flux/src/main/java/com/iluwatar/flux/app/App.java b/flux/src/main/java/com/iluwatar/flux/app/App.java
index a567a92d3..0f301a2ae 100644
--- a/flux/src/main/java/com/iluwatar/flux/app/App.java
+++ b/flux/src/main/java/com/iluwatar/flux/app/App.java
@@ -9,43 +9,45 @@ import com.iluwatar.flux.view.MenuView;
/**
*
- * Flux is the application architecture that Facebook uses for building client-side web
- * applications. Flux eschews MVC in favor of a unidirectional data flow. When a user interacts with
- * a React view, the view propagates an action through a central dispatcher, to the various stores that
- * hold the application's data and business logic, which updates all of the views that are affected.
+ * Flux is the application architecture that Facebook uses for building client-side web
+ * applications. Flux eschews MVC in favor of a unidirectional data flow. When a user interacts with
+ * a React view, the view propagates an action through a central dispatcher, to the various stores
+ * that hold the application's data and business logic, which updates all of the views that are
+ * affected.
*
- * This example has two views: menu and content. They represent typical main menu and content area of
- * a web page. When menu item is clicked it triggers events through the dispatcher. The events are
- * received and handled by the stores updating their data as needed. The stores then notify the views
- * that they should rerender themselves.
+ * This example has two views: menu and content. They represent typical main menu and content area
+ * of a web page. When menu item is clicked it triggers events through the dispatcher. The events
+ * are received and handled by the stores updating their data as needed. The stores then notify the
+ * views that they should rerender themselves.
*
* http://facebook.github.io/flux/docs/overview.html
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
-
- // initialize and wire the system
- MenuStore menuStore = new MenuStore();
- Dispatcher.getInstance().registerStore(menuStore);
- ContentStore contentStore = new ContentStore();
- Dispatcher.getInstance().registerStore(contentStore);
- MenuView menuView = new MenuView();
- menuStore.registerView(menuView);
- ContentView 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);
- }
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+
+ // initialize and wire the system
+ MenuStore menuStore = new MenuStore();
+ Dispatcher.getInstance().registerStore(menuStore);
+ ContentStore contentStore = new ContentStore();
+ Dispatcher.getInstance().registerStore(contentStore);
+ MenuView menuView = new MenuView();
+ menuStore.registerView(menuView);
+ ContentView 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);
+ }
}
diff --git a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java
index 8bf03e4b0..26c836b0e 100644
--- a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java
+++ b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java
@@ -16,37 +16,36 @@ import com.iluwatar.flux.store.Store;
*
*/
public class Dispatcher {
-
- private static Dispatcher instance = new Dispatcher();
-
- private List stores = new LinkedList<>();
-
- private Dispatcher() {
- }
- public static Dispatcher getInstance() {
- return instance;
- }
-
- public void registerStore(Store store) {
- stores.add(store);
- }
-
- public void menuItemSelected(MenuItem menuItem) {
- dispatchAction(new MenuAction(menuItem));
- switch (menuItem) {
- case HOME:
- case PRODUCTS:
- default:
- dispatchAction(new ContentAction(Content.PRODUCTS));
- break;
- case COMPANY:
- dispatchAction(new ContentAction(Content.COMPANY));
- break;
- }
- }
-
- private void dispatchAction(Action action) {
- stores.stream().forEach((store) -> store.onAction(action));
- }
+ private static Dispatcher instance = new Dispatcher();
+
+ private List stores = new LinkedList<>();
+
+ private Dispatcher() {}
+
+ public static Dispatcher getInstance() {
+ return instance;
+ }
+
+ public void registerStore(Store store) {
+ stores.add(store);
+ }
+
+ public void menuItemSelected(MenuItem menuItem) {
+ dispatchAction(new MenuAction(menuItem));
+ switch (menuItem) {
+ case HOME:
+ case PRODUCTS:
+ default:
+ dispatchAction(new ContentAction(Content.PRODUCTS));
+ break;
+ case COMPANY:
+ dispatchAction(new ContentAction(Content.COMPANY));
+ break;
+ }
+ }
+
+ private void dispatchAction(Action action) {
+ stores.stream().forEach((store) -> store.onAction(action));
+ }
}
diff --git a/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java b/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java
index 15d031abd..621dc4c0c 100644
--- a/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java
+++ b/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java
@@ -12,18 +12,18 @@ import com.iluwatar.flux.action.ContentAction;
*/
public class ContentStore extends Store {
- private Content content = Content.PRODUCTS;
+ private Content content = Content.PRODUCTS;
- @Override
- public void onAction(Action action) {
- if (action.getType().equals(ActionType.CONTENT_CHANGED)) {
- ContentAction contentAction = (ContentAction) action;
- content = contentAction.getContent();
- notifyChange();
- }
- }
-
- public Content getContent() {
- return content;
- }
+ @Override
+ public void onAction(Action action) {
+ if (action.getType().equals(ActionType.CONTENT_CHANGED)) {
+ ContentAction contentAction = (ContentAction) action;
+ content = contentAction.getContent();
+ notifyChange();
+ }
+ }
+
+ public Content getContent() {
+ return content;
+ }
}
diff --git a/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java b/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java
index 3e614ac73..23d27bcde 100644
--- a/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java
+++ b/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java
@@ -12,18 +12,18 @@ import com.iluwatar.flux.action.MenuItem;
*/
public class MenuStore extends Store {
- private MenuItem selected = MenuItem.HOME;
-
- @Override
- public void onAction(Action action) {
- if (action.getType().equals(ActionType.MENU_ITEM_SELECTED)) {
- MenuAction menuAction = (MenuAction) action;
- selected = menuAction.getMenuItem();
- notifyChange();
- }
- }
-
- public MenuItem getSelected() {
- return selected;
- }
+ private MenuItem selected = MenuItem.HOME;
+
+ @Override
+ public void onAction(Action action) {
+ if (action.getType().equals(ActionType.MENU_ITEM_SELECTED)) {
+ MenuAction menuAction = (MenuAction) action;
+ selected = menuAction.getMenuItem();
+ notifyChange();
+ }
+ }
+
+ public MenuItem getSelected() {
+ return selected;
+ }
}
diff --git a/flux/src/main/java/com/iluwatar/flux/store/Store.java b/flux/src/main/java/com/iluwatar/flux/store/Store.java
index 326af404b..0562405b2 100644
--- a/flux/src/main/java/com/iluwatar/flux/store/Store.java
+++ b/flux/src/main/java/com/iluwatar/flux/store/Store.java
@@ -12,16 +12,16 @@ import com.iluwatar.flux.view.View;
*
*/
public abstract class Store {
-
- private List views = new LinkedList<>();
-
- public abstract void onAction(Action action);
- public void registerView(View view) {
- views.add(view);
- }
-
- protected void notifyChange() {
- views.stream().forEach((view) -> view.storeChanged(this));
- }
+ private List views = new LinkedList<>();
+
+ public abstract void onAction(Action action);
+
+ public void registerView(View view) {
+ views.add(view);
+ }
+
+ protected void notifyChange() {
+ views.stream().forEach((view) -> view.storeChanged(this));
+ }
}
diff --git a/flux/src/main/java/com/iluwatar/flux/view/ContentView.java b/flux/src/main/java/com/iluwatar/flux/view/ContentView.java
index b12c8b7a2..5718a07f3 100644
--- a/flux/src/main/java/com/iluwatar/flux/view/ContentView.java
+++ b/flux/src/main/java/com/iluwatar/flux/view/ContentView.java
@@ -11,17 +11,17 @@ import com.iluwatar.flux.store.Store;
*/
public class ContentView implements View {
- private Content content = Content.PRODUCTS;
+ private Content content = Content.PRODUCTS;
- @Override
- public void storeChanged(Store store) {
- ContentStore contentStore = (ContentStore) store;
- content = contentStore.getContent();
- render();
- }
+ @Override
+ public void storeChanged(Store store) {
+ ContentStore contentStore = (ContentStore) store;
+ content = contentStore.getContent();
+ render();
+ }
- @Override
- public void render() {
- System.out.println(content.toString());
- }
+ @Override
+ public void render() {
+ System.out.println(content.toString());
+ }
}
diff --git a/flux/src/main/java/com/iluwatar/flux/view/MenuView.java b/flux/src/main/java/com/iluwatar/flux/view/MenuView.java
index f37d21bb9..20f8ce03d 100644
--- a/flux/src/main/java/com/iluwatar/flux/view/MenuView.java
+++ b/flux/src/main/java/com/iluwatar/flux/view/MenuView.java
@@ -12,27 +12,27 @@ import com.iluwatar.flux.store.Store;
*/
public class MenuView implements View {
- private MenuItem selected = MenuItem.HOME;
-
- @Override
- public void storeChanged(Store store) {
- MenuStore menuStore = (MenuStore) store;
- selected = menuStore.getSelected();
- render();
- }
+ private MenuItem selected = MenuItem.HOME;
- @Override
- public void render() {
- for (MenuItem item: MenuItem.values()) {
- if (selected.equals(item)) {
- System.out.println(String.format("* %s", item.toString()));
- } else {
- System.out.println(item.toString());
- }
- }
- }
-
- public void itemClicked(MenuItem item) {
- Dispatcher.getInstance().menuItemSelected(item);
- }
+ @Override
+ public void storeChanged(Store store) {
+ MenuStore menuStore = (MenuStore) store;
+ selected = menuStore.getSelected();
+ render();
+ }
+
+ @Override
+ public void render() {
+ for (MenuItem item : MenuItem.values()) {
+ if (selected.equals(item)) {
+ System.out.println(String.format("* %s", item.toString()));
+ } else {
+ System.out.println(item.toString());
+ }
+ }
+ }
+
+ public void itemClicked(MenuItem item) {
+ Dispatcher.getInstance().menuItemSelected(item);
+ }
}
diff --git a/flux/src/main/java/com/iluwatar/flux/view/View.java b/flux/src/main/java/com/iluwatar/flux/view/View.java
index 4eb6ee3fb..a642b5b2c 100644
--- a/flux/src/main/java/com/iluwatar/flux/view/View.java
+++ b/flux/src/main/java/com/iluwatar/flux/view/View.java
@@ -9,7 +9,7 @@ import com.iluwatar.flux.store.Store;
*/
public interface View {
- public void storeChanged(Store store);
+ public void storeChanged(Store store);
- public void render();
+ public void render();
}
diff --git a/flux/src/test/java/com/iluwatar/flux/app/AppTest.java b/flux/src/test/java/com/iluwatar/flux/app/AppTest.java
index ba4b592a1..918c76acd 100644
--- a/flux/src/test/java/com/iluwatar/flux/app/AppTest.java
+++ b/flux/src/test/java/com/iluwatar/flux/app/AppTest.java
@@ -10,10 +10,10 @@ import com.iluwatar.flux.app.App;
*
*/
public class AppTest {
-
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java
index e87f2e6cf..15206a84a 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java
@@ -5,53 +5,52 @@ import java.util.List;
/**
*
- * AlchemistShop holds potions on its shelves.
- * It uses PotionFactory to provide the potions.
+ * AlchemistShop holds potions on its shelves. It uses PotionFactory to provide the potions.
*
*/
public class AlchemistShop {
- private List topShelf;
- private List bottomShelf;
+ private List topShelf;
+ private List bottomShelf;
- public AlchemistShop() {
- topShelf = new ArrayList<>();
- bottomShelf = new ArrayList<>();
- fillShelves();
- }
+ public AlchemistShop() {
+ topShelf = new ArrayList<>();
+ bottomShelf = new ArrayList<>();
+ fillShelves();
+ }
- private void fillShelves() {
+ private void fillShelves() {
- PotionFactory factory = new PotionFactory();
+ PotionFactory factory = new PotionFactory();
- topShelf.add(factory.createPotion(PotionType.INVISIBILITY));
- topShelf.add(factory.createPotion(PotionType.INVISIBILITY));
- topShelf.add(factory.createPotion(PotionType.STRENGTH));
- topShelf.add(factory.createPotion(PotionType.HEALING));
- topShelf.add(factory.createPotion(PotionType.INVISIBILITY));
- topShelf.add(factory.createPotion(PotionType.STRENGTH));
- topShelf.add(factory.createPotion(PotionType.HEALING));
- topShelf.add(factory.createPotion(PotionType.HEALING));
+ topShelf.add(factory.createPotion(PotionType.INVISIBILITY));
+ topShelf.add(factory.createPotion(PotionType.INVISIBILITY));
+ topShelf.add(factory.createPotion(PotionType.STRENGTH));
+ topShelf.add(factory.createPotion(PotionType.HEALING));
+ topShelf.add(factory.createPotion(PotionType.INVISIBILITY));
+ topShelf.add(factory.createPotion(PotionType.STRENGTH));
+ topShelf.add(factory.createPotion(PotionType.HEALING));
+ topShelf.add(factory.createPotion(PotionType.HEALING));
- bottomShelf.add(factory.createPotion(PotionType.POISON));
- bottomShelf.add(factory.createPotion(PotionType.POISON));
- bottomShelf.add(factory.createPotion(PotionType.POISON));
- bottomShelf.add(factory.createPotion(PotionType.HOLY_WATER));
- bottomShelf.add(factory.createPotion(PotionType.HOLY_WATER));
- }
+ bottomShelf.add(factory.createPotion(PotionType.POISON));
+ bottomShelf.add(factory.createPotion(PotionType.POISON));
+ bottomShelf.add(factory.createPotion(PotionType.POISON));
+ bottomShelf.add(factory.createPotion(PotionType.HOLY_WATER));
+ bottomShelf.add(factory.createPotion(PotionType.HOLY_WATER));
+ }
- public void enumerate() {
+ public void enumerate() {
- System.out.println("Enumerating top shelf potions\n");
+ System.out.println("Enumerating top shelf potions\n");
- for (Potion p : topShelf) {
- p.drink();
- }
+ for (Potion p : topShelf) {
+ p.drink();
+ }
- System.out.println("\nEnumerating bottom shelf potions\n");
+ System.out.println("\nEnumerating bottom shelf potions\n");
- for (Potion p : bottomShelf) {
- p.drink();
- }
- }
+ for (Potion p : bottomShelf) {
+ p.drink();
+ }
+ }
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/App.java b/flyweight/src/main/java/com/iluwatar/flyweight/App.java
index c08ba78a3..211e031df 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/App.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/App.java
@@ -2,26 +2,27 @@ package com.iluwatar.flyweight;
/**
*
- * Flyweight pattern is useful when the program needs a huge amount of objects.
- * It provides means to decrease resource usage by sharing object instances.
+ * Flyweight pattern is useful when the program needs a huge amount of objects. It provides means to
+ * decrease resource usage by sharing object instances.
*
- * In this example {@link AlchemistShop} has great amount of potions on its shelves.
- * To fill the shelves {@link AlchemistShop} uses {@link PotionFactory} (which represents
- * the Flyweight in this example). Internally {@link PotionFactory} holds a map
- * of the potions and lazily creates new ones when requested.
+ * In this example {@link AlchemistShop} has great amount of potions on its shelves. To fill the
+ * shelves {@link AlchemistShop} uses {@link PotionFactory} (which represents the Flyweight in this
+ * example). Internally {@link PotionFactory} holds a map of the potions and lazily creates new ones
+ * when requested.
*
- * To enable safe sharing, between clients and threads, Flyweight objects must
- * be immutable. Flyweight objects are by definition value objects.
+ * To enable safe sharing, between clients and threads, Flyweight objects must be immutable.
+ * Flyweight objects are by definition value objects.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- AlchemistShop alchemistShop = new AlchemistShop();
- alchemistShop.enumerate();
- }
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ AlchemistShop alchemistShop = new AlchemistShop();
+ alchemistShop.enumerate();
+ }
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java
index a5f8f4fb8..c458e19b5 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java
@@ -7,10 +7,8 @@ package com.iluwatar.flyweight;
*/
public class HealingPotion implements Potion {
- @Override
- public void drink() {
- System.out.println("You feel healed. (Potion="
- + System.identityHashCode(this) + ")");
- }
-
+ @Override
+ public void drink() {
+ System.out.println("You feel healed. (Potion=" + System.identityHashCode(this) + ")");
+ }
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java
index 750e3c568..45034c29a 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java
@@ -7,10 +7,8 @@ package com.iluwatar.flyweight;
*/
public class HolyWaterPotion implements Potion {
- @Override
- public void drink() {
- System.out.println("You feel blessed. (Potion="
- + System.identityHashCode(this) + ")");
- }
-
+ @Override
+ public void drink() {
+ System.out.println("You feel blessed. (Potion=" + System.identityHashCode(this) + ")");
+ }
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java
index db9d261d5..ca8de16e9 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java
@@ -7,10 +7,8 @@ package com.iluwatar.flyweight;
*/
public class InvisibilityPotion implements Potion {
- @Override
- public void drink() {
- System.out.println("You become invisible. (Potion="
- + System.identityHashCode(this) + ")");
- }
-
+ @Override
+ public void drink() {
+ System.out.println("You become invisible. (Potion=" + System.identityHashCode(this) + ")");
+ }
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java
index dfcd3c38d..f1a1855f8 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java
@@ -7,10 +7,8 @@ package com.iluwatar.flyweight;
*/
public class PoisonPotion implements Potion {
- @Override
- public void drink() {
- System.out.println("Urgh! This is poisonous. (Potion="
- + System.identityHashCode(this) + ")");
- }
-
+ @Override
+ public void drink() {
+ System.out.println("Urgh! This is poisonous. (Potion=" + System.identityHashCode(this) + ")");
+ }
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java b/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java
index c4110201c..1ba72431a 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java
@@ -7,5 +7,5 @@ package com.iluwatar.flyweight;
*/
public interface Potion {
- void drink();
+ void drink();
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java
index 20ec110e3..8154da984 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java
@@ -5,48 +5,47 @@ import java.util.Map;
/**
*
- * PotionFactory is the Flyweight in this example.
- * It minimizes memory use by sharing object instances.
- * It holds a map of potion instances and new potions
- * are created only when none of the type already exists.
+ * PotionFactory is the Flyweight in this example. It minimizes memory use by sharing object
+ * instances. It holds a map of potion instances and new potions are created only when none of the
+ * type already exists.
*
*/
public class PotionFactory {
- private final Map potions;
+ private final Map potions;
- public PotionFactory() {
- potions = new EnumMap<>(PotionType.class);
- }
+ public PotionFactory() {
+ potions = new EnumMap<>(PotionType.class);
+ }
- Potion createPotion(PotionType type) {
- Potion potion = potions.get(type);
- if (potion == null) {
- switch (type) {
- case HEALING:
- potion = new HealingPotion();
- potions.put(type, potion);
- break;
- case HOLY_WATER:
- potion = new HolyWaterPotion();
- potions.put(type, potion);
- break;
- case INVISIBILITY:
- potion = new InvisibilityPotion();
- potions.put(type, potion);
- break;
- case POISON:
- potion = new PoisonPotion();
- potions.put(type, potion);
- break;
- case STRENGTH:
- potion = new StrengthPotion();
- potions.put(type, potion);
- break;
- default:
- break;
- }
- }
- return potion;
- }
+ Potion createPotion(PotionType type) {
+ Potion potion = potions.get(type);
+ if (potion == null) {
+ switch (type) {
+ case HEALING:
+ potion = new HealingPotion();
+ potions.put(type, potion);
+ break;
+ case HOLY_WATER:
+ potion = new HolyWaterPotion();
+ potions.put(type, potion);
+ break;
+ case INVISIBILITY:
+ potion = new InvisibilityPotion();
+ potions.put(type, potion);
+ break;
+ case POISON:
+ potion = new PoisonPotion();
+ potions.put(type, potion);
+ break;
+ case STRENGTH:
+ potion = new StrengthPotion();
+ potions.put(type, potion);
+ break;
+ default:
+ break;
+ }
+ }
+ return potion;
+ }
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PotionType.java b/flyweight/src/main/java/com/iluwatar/flyweight/PotionType.java
index bbb9b6521..0aade3826 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/PotionType.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/PotionType.java
@@ -7,5 +7,5 @@ package com.iluwatar.flyweight;
*/
public enum PotionType {
- HEALING, INVISIBILITY, STRENGTH, HOLY_WATER, POISON
+ HEALING, INVISIBILITY, STRENGTH, HOLY_WATER, POISON
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java
index 49083cf7c..f729668d4 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java
@@ -7,9 +7,8 @@ package com.iluwatar.flyweight;
*/
public class StrengthPotion implements Potion {
- @Override
- public void drink() {
- System.out.println("You feel strong. (Potion="
- + System.identityHashCode(this) + ")");
- }
+ @Override
+ public void drink() {
+ System.out.println("You feel strong. (Potion=" + System.identityHashCode(this) + ")");
+ }
}
diff --git a/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java b/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java
index f3b033ba7..16fdb005e 100644
--- a/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java
+++ b/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.flyweight.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java
index b8cec89e3..80f2eefb2 100644
--- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java
+++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java
@@ -8,122 +8,120 @@ import java.util.concurrent.LinkedBlockingQueue;
* {@link AsyncTask} and {@link AsynchronousService}.
*
*
- * PROBLEM
- *
- * A concurrent system have a mixture of short duration, mid duration and long duration tasks.
- * Mid or long duration tasks should be performed asynchronously to meet quality of service
+ * PROBLEM
+ * A concurrent system have a mixture of short duration, mid duration and long duration tasks. Mid
+ * or long duration tasks should be performed asynchronously to meet quality of service
* requirements.
- *
- *
INTENT
- *
- * The intent of this pattern is to separate the the synchronous and asynchronous processing
- * in the concurrent application by introducing two intercommunicating layers - one for sync
- * and one for async. This simplifies the programming without unduly affecting the performance.
- *
+ *
*
- * APPLICABILITY
- *
+ * INTENT
+ * The intent of this pattern is to separate the the synchronous and asynchronous processing in the
+ * concurrent application by introducing two intercommunicating layers - one for sync and one for
+ * async. This simplifies the programming without unduly affecting the performance.
+ *
+ *
+ * APPLICABILITY
*
* - UNIX network subsystems - In operating systems network operations are carried out
* asynchronously with help of hardware level interrupts.
- * - CORBA - At the asynchronous layer one thread is associated with each socket that is
- * connected to the client. Thread blocks waiting for CORBA requests from the client. On receiving
- * request it is inserted in the queuing layer which is then picked up by synchronous layer which
- * processes the request and sends response back to the client.
- * - Android AsyncTask framework - Framework provides a way to execute long running blocking calls,
- * such as downloading a file, in background threads so that the UI thread remains free to respond
- * to user inputs.
- *
- *
+ * CORBA - At the asynchronous layer one thread is associated with each socket that is connected
+ * to the client. Thread blocks waiting for CORBA requests from the client. On receiving request it
+ * is inserted in the queuing layer which is then picked up by synchronous layer which processes the
+ * request and sends response back to the client.
+ * Android AsyncTask framework - Framework provides a way to execute long running blocking
+ * calls, such as downloading a file, in background threads so that the UI thread remains free to
+ * respond to user inputs.
+ *
+ *
*
- * IMPLEMENTATION
- *
- * The main method creates an asynchronous service which does not block the main thread while
- * the task is being performed. The main thread continues its work which is similar to Async Method
- * Invocation pattern. The difference between them is that there is a queuing layer between Asynchronous
- * layer and synchronous layer, which allows for different communication patterns between both layers.
- * Such as Priority Queue can be used as queuing layer to prioritize the way tasks are executed.
- * Our implementation is just one simple way of implementing this pattern, there are many variants possible
- * as described in its applications.
+ * IMPLEMENTATION
+ * The main method creates an asynchronous service which does not block the main thread while the
+ * task is being performed. The main thread continues its work which is similar to Async Method
+ * Invocation pattern. The difference between them is that there is a queuing layer between
+ * Asynchronous layer and synchronous layer, which allows for different communication patterns
+ * between both layers. Such as Priority Queue can be used as queuing layer to prioritize the way
+ * tasks are executed. Our implementation is just one simple way of implementing this pattern, there
+ * are many variants possible as described in its applications.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- AsynchronousService 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));
- }
-
- /**
- *
- * ArithmeticSumTask
- *
- */
- static class ArithmeticSumTask implements AsyncTask {
- private long n;
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ AsynchronousService 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));
- public ArithmeticSumTask(long n) {
- this.n = n;
- }
+ /*
+ * 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));
+ }
- /*
- * 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(n);
- }
+ /**
+ *
+ * ArithmeticSumTask
+ *
+ */
+ static class ArithmeticSumTask implements AsyncTask {
+ private long n;
- /*
- * 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 (n < 0) {
- throw new IllegalArgumentException("n is less than 0");
- }
- }
+ public ArithmeticSumTask(long n) {
+ this.n = n;
+ }
- @Override
- public void onPostCall(Long result) {
- // Handle the result of computation
- System.out.println(result);
- }
+ /*
+ * 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(n);
+ }
- @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) {
- }
- return (i) * (i + 1) / 2;
- }
+ /*
+ * 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 (n < 0) {
+ throw new IllegalArgumentException("n is less than 0");
+ }
+ }
+
+ @Override
+ public void onPostCall(Long result) {
+ // Handle the result of computation
+ System.out.println(result);
+ }
+
+ @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) {
+ }
+ return (i) * (i + 1) / 2;
+ }
}
diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java
index 8ed7376b6..fb63e9653 100644
--- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java
+++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java
@@ -3,42 +3,42 @@ package com.iluwatar.halfsynchalfasync;
import java.util.concurrent.Callable;
/**
- * Represents some computation that is performed asynchronously and its result.
- * The computation is typically done is background threads and the result is posted
- * back in form of callback. The callback does not implement {@code isComplete}, {@code cancel}
- * as it is out of scope of this pattern.
+ * Represents some computation that is performed asynchronously and its result. The computation is
+ * typically done is background threads and the result is posted back in form of callback. The
+ * callback does not implement {@code isComplete}, {@code cancel} as it is out of scope of this
+ * pattern.
*
* @param type of result
*/
public interface AsyncTask extends Callable {
- /**
- * Is called in context of caller thread before call to {@link #call()}. Large
- * tasks should not be performed in this method as it will block the caller thread.
- * Small tasks such as validations can be performed here so that the performance penalty
- * of context switching is not incurred in case of invalid requests.
- */
- void onPreCall();
-
- /**
- * A callback called after the result is successfully computed by {@link #call()}. In our
- * implementation this method is called in context of background thread but in some variants,
- * such as Android where only UI thread can change the state of UI widgets, this method is called
- * in context of UI thread.
- */
- void onPostCall(O result);
-
- /**
- * A callback called if computing the task resulted in some exception. This method
- * is called when either of {@link #call()} or {@link #onPreCall()} throw any exception.
- *
- * @param throwable error cause
- */
- void onError(Throwable throwable);
-
- /**
- * This is where the computation of task should reside. This method is called in context
- * of background thread.
- */
- @Override
- O call() throws Exception;
+ /**
+ * Is called in context of caller thread before call to {@link #call()}. Large tasks should not be
+ * performed in this method as it will block the caller thread. Small tasks such as validations
+ * can be performed here so that the performance penalty of context switching is not incurred in
+ * case of invalid requests.
+ */
+ void onPreCall();
+
+ /**
+ * A callback called after the result is successfully computed by {@link #call()}. In our
+ * implementation this method is called in context of background thread but in some variants, such
+ * as Android where only UI thread can change the state of UI widgets, this method is called in
+ * context of UI thread.
+ */
+ void onPostCall(O result);
+
+ /**
+ * A callback called if computing the task resulted in some exception. This method is called when
+ * either of {@link #call()} or {@link #onPreCall()} throw any exception.
+ *
+ * @param throwable error cause
+ */
+ void onError(Throwable throwable);
+
+ /**
+ * This is where the computation of task should reside. This method is called in context of
+ * background thread.
+ */
+ @Override
+ O call() throws Exception;
}
diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java
index 6c36354d0..457dffa20 100644
--- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java
+++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java
@@ -9,67 +9,67 @@ import java.util.concurrent.TimeUnit;
/**
* This is the asynchronous layer which does not block when a new request arrives. It just passes
- * the request to the synchronous layer which consists of a queue i.e. a {@link BlockingQueue} and
- * a pool of threads i.e. {@link ThreadPoolExecutor}. Out of this pool of worker threads one of the
- * thread picks up the task and executes it synchronously in background and the result is posted back
- * to the caller via callback.
+ * the request to the synchronous layer which consists of a queue i.e. a {@link BlockingQueue} and a
+ * pool of threads i.e. {@link ThreadPoolExecutor}. Out of this pool of worker threads one of the
+ * thread picks up the task and executes it synchronously in background and the result is posted
+ * back to the caller via callback.
*/
public 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 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 workQueue) {
- service = new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, workQueue);
- }
-
+ /*
+ * 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 ExecutorService service;
- /**
- * A non-blocking method which performs the task provided in background and returns immediately.
- *
- * 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)}.
- *
- * NOTE: The results are posted back in the context of background thread in this implementation.
- */
- public void execute(final AsyncTask task) {
- try {
- // some small tasks such as validation can be performed here.
- task.onPreCall();
- } catch (Exception e) {
- task.onError(e);
- }
+ /**
+ * 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 workQueue) {
+ service = new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, workQueue);
+ }
- service.submit(new FutureTask(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());
- }
- }
- });
- }
+
+ /**
+ * A non-blocking method which performs the task provided in background and returns immediately.
+ *
+ * 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)}.
+ *
+ * NOTE: The results are posted back in the context of background thread in this implementation.
+ */
+ public void execute(final AsyncTask task) {
+ try {
+ // some small tasks such as validation can be performed here.
+ task.onPreCall();
+ } catch (Exception e) {
+ task.onError(e);
+ }
+
+ service.submit(new FutureTask(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());
+ }
+ }
+ });
+ }
}
diff --git a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java
index a72417aff..4104bdaf2 100644
--- a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java
+++ b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java
@@ -11,8 +11,8 @@ import org.junit.Test;
*/
public class AppTest {
- @Test
- public void test() throws InterruptedException, ExecutionException {
- App.main(null);
- }
+ @Test
+ public void test() throws InterruptedException, ExecutionException {
+ App.main(null);
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java
index 2c32772fa..1dd31b201 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java
@@ -1,46 +1,44 @@
package com.iluwatar.intercepting.filter;
/**
- * Base class for order processing filters.
- * Handles chain management.
+ * Base class for order processing filters. Handles chain management.
*
*/
public abstract class AbstractFilter implements Filter {
- private Filter next;
-
- public AbstractFilter() {
- }
+ private Filter next;
- public AbstractFilter(Filter next) {
- this.next = next;
- }
-
- @Override
- public void setNext(Filter filter) {
- this.next = filter;
- }
-
- @Override
- public Filter getNext() {
- return next;
- }
+ public AbstractFilter() {}
- @Override
- public Filter getLast() {
- Filter last = this;
- while (last.getNext() != null) {
- last = last.getNext();
- }
- return last;
- }
-
- @Override
- public String execute(Order order) {
- if (getNext() != null) {
- return getNext().execute(order);
- } else {
- return "";
- }
- }
+ public AbstractFilter(Filter next) {
+ this.next = next;
+ }
+
+ @Override
+ public void setNext(Filter filter) {
+ this.next = filter;
+ }
+
+ @Override
+ public Filter getNext() {
+ return next;
+ }
+
+ @Override
+ public Filter getLast() {
+ Filter last = this;
+ while (last.getNext() != null) {
+ last = last.getNext();
+ }
+ return last;
+ }
+
+ @Override
+ public String execute(Order order) {
+ if (getNext() != null) {
+ return getNext().execute(order);
+ } else {
+ return "";
+ }
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java
index 0bd66c047..c1aa0780b 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java
@@ -1,19 +1,20 @@
package com.iluwatar.intercepting.filter;
/**
- * Concrete implementation of filter
- * This filter is responsible for checking/filtering the input in the address field.
+ * Concrete implementation of filter This filter is responsible for checking/filtering the input in
+ * the address field.
+ *
* @author joshzambales
*
*/
public class AddressFilter extends AbstractFilter {
-
- @Override
- public String execute(Order order) {
- String result = super.execute(order);
- if (order.getAddress() == null || order.getAddress().isEmpty()) {
- return result + "Invalid address! ";
- } else
- return result;
- }
+
+ @Override
+ public String execute(Order order) {
+ String result = super.execute(order);
+ if (order.getAddress() == null || order.getAddress().isEmpty()) {
+ return result + "Invalid address! ";
+ } else
+ return result;
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java
index c913da66c..817ae7587 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java
@@ -2,50 +2,46 @@ package com.iluwatar.intercepting.filter;
/**
*
- * When a request enters a Web application, it often must pass several entrance
- * tests prior to the main processing stage. For example,
- * - Has the client been authenticated?
- * - Does the client have a valid session?
- * - Is the client's IP address from a trusted network?
- * - Does the request path violate any constraints?
- * - What encoding does the client use to send the data?
- * - Do we support the browser type of the client?
- * Some of these checks are tests, resulting in a yes or no answer that determines
- * whether processing will continue. Other checks manipulate the incoming data
+ * When a request enters a Web application, it often must pass several entrance tests prior to the
+ * main processing stage. For example, - Has the client been authenticated? - Does the client have a
+ * valid session? - Is the client's IP address from a trusted network? - Does the request path
+ * violate any constraints? - What encoding does the client use to send the data? - Do we support
+ * the browser type of the client? Some of these checks are tests, resulting in a yes or no answer
+ * that determines whether processing will continue. Other checks manipulate the incoming data
* stream into a form suitable for processing.
*
- * The classic solution consists of a series of conditional checks, with any failed
- * check aborting the request. Nested if/else statements are a standard strategy,
- * but this solution leads to code fragility and a copy-and-paste style of programming,
- * because the flow of the filtering and the action of the filters is compiled into
- * the application.
+ * The classic solution consists of a series of conditional checks, with any failed check aborting
+ * the request. Nested if/else statements are a standard strategy, but this solution leads to code
+ * fragility and a copy-and-paste style of programming, because the flow of the filtering and the
+ * action of the filters is compiled into the application.
*
- * The key to solving this problem in a flexible and unobtrusive manner is to have a
- * simple mechanism for adding and removing processing components, in which each
- * component completes a specific filtering action. This is the Intercepting Filter
- * pattern in action.
+ * The key to solving this problem in a flexible and unobtrusive manner is to have a simple
+ * mechanism for adding and removing processing components, in which each component completes a
+ * specific filtering action. This is the Intercepting Filter pattern in action.
*
- * In this example we check whether the order request is valid through pre-processing
- * done via {@link Filter}. Each field has its own corresponding {@link Filter}
+ * In this example we check whether the order request is valid through pre-processing done via
+ * {@link Filter}. Each field has its own corresponding {@link Filter}
*
+ *
* @author joshzambales
*
*/
-public class App{
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- FilterManager filterManager = new FilterManager(new Target());
- filterManager.addFilter(new NameFilter());
- filterManager.addFilter(new ContactFilter());
- filterManager.addFilter(new AddressFilter());
- filterManager.addFilter(new DepositFilter());
- filterManager.addFilter(new OrderFilter());
+public class App {
- Client client = new Client();
- client.setFilterManager(filterManager);
- }
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ FilterManager filterManager = new FilterManager(new Target());
+ filterManager.addFilter(new NameFilter());
+ filterManager.addFilter(new ContactFilter());
+ filterManager.addFilter(new AddressFilter());
+ filterManager.addFilter(new DepositFilter());
+ filterManager.addFilter(new OrderFilter());
+
+ Client client = new Client();
+ client.setFilterManager(filterManager);
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java
index 0125d1b9d..02499ed0a 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java
@@ -15,93 +15,95 @@ import javax.swing.JTextField;
import javax.swing.SwingUtilities;
/**
- * The Client class is responsible for handling the input and running them through filters inside the {@link FilterManager}.
+ * The Client class is responsible for handling the input and running them through filters inside
+ * the {@link FilterManager}.
*
- * This is where {@link Filter}s come to play as the client pre-processes the request before being displayed in the {@link Target}.
+ * This is where {@link Filter}s come to play as the client pre-processes the request before being
+ * displayed in the {@link Target}.
*
* @author joshzambales
*
*/
public class Client extends JFrame {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- private FilterManager filterManager;
- private JLabel jl;
- private JTextField[] jtFields;
- private JTextArea[] jtAreas;
- private JButton clearButton, processButton;
+ private FilterManager filterManager;
+ private JLabel jl;
+ private JTextField[] jtFields;
+ private JTextArea[] jtAreas;
+ private JButton clearButton, processButton;
- public Client() {
- super("Client System");
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- setSize(300, 300);
- jl = new JLabel("RUNNING...");
- jtFields = new JTextField[3];
- for (int i = 0; i < 3; i++) {
- jtFields[i] = new JTextField();
- }
- jtAreas = new JTextArea[2];
- for (int i = 0; i < 2; i++) {
- jtAreas[i] = new JTextArea();
- }
- clearButton = new JButton("Clear");
- processButton = new JButton("Process");
+ public Client() {
+ super("Client System");
+ setDefaultCloseOperation(EXIT_ON_CLOSE);
+ setSize(300, 300);
+ jl = new JLabel("RUNNING...");
+ jtFields = new JTextField[3];
+ for (int i = 0; i < 3; i++) {
+ jtFields[i] = new JTextField();
+ }
+ jtAreas = new JTextArea[2];
+ for (int i = 0; i < 2; i++) {
+ jtAreas[i] = new JTextArea();
+ }
+ clearButton = new JButton("Clear");
+ processButton = new JButton("Process");
- setup();
- }
+ setup();
+ }
- private void setup() {
- setLayout(new BorderLayout());
- JPanel panel = new JPanel();
- add(jl, BorderLayout.SOUTH);
- add(panel, BorderLayout.CENTER);
- panel.setLayout(new GridLayout(6, 2));
- panel.add(new JLabel("Name"));
- panel.add(jtFields[0]);
- panel.add(new JLabel("Contact Number"));
- panel.add(jtFields[1]);
- panel.add(new JLabel("Address"));
- panel.add(jtAreas[0]);
- panel.add(new JLabel("Deposit Number"));
- panel.add(jtFields[2]);
- panel.add(new JLabel("Order"));
- panel.add(jtAreas[1]);
- panel.add(clearButton);
- panel.add(processButton);
+ private void setup() {
+ setLayout(new BorderLayout());
+ JPanel panel = new JPanel();
+ add(jl, BorderLayout.SOUTH);
+ add(panel, BorderLayout.CENTER);
+ panel.setLayout(new GridLayout(6, 2));
+ panel.add(new JLabel("Name"));
+ panel.add(jtFields[0]);
+ panel.add(new JLabel("Contact Number"));
+ panel.add(jtFields[1]);
+ panel.add(new JLabel("Address"));
+ panel.add(jtAreas[0]);
+ panel.add(new JLabel("Deposit Number"));
+ panel.add(jtFields[2]);
+ panel.add(new JLabel("Order"));
+ panel.add(jtAreas[1]);
+ panel.add(clearButton);
+ panel.add(processButton);
- clearButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- for (JTextArea i : jtAreas) {
- i.setText("");
- }
- for (JTextField i : jtFields) {
- i.setText("");
- }
- }
- });
+ clearButton.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ for (JTextArea i : jtAreas) {
+ i.setText("");
+ }
+ for (JTextField i : jtFields) {
+ i.setText("");
+ }
+ }
+ });
- processButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- Order order = new Order(jtFields[0].getText(), jtFields[1]
- .getText(), jtAreas[0].getText(),
- jtFields[2].getText(), jtAreas[1].getText());
- jl.setText(sendRequest(order));
- }
- });
+ processButton.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ Order order =
+ new Order(jtFields[0].getText(), jtFields[1].getText(), jtAreas[0].getText(),
+ jtFields[2].getText(), jtAreas[1].getText());
+ jl.setText(sendRequest(order));
+ }
+ });
- JRootPane rootPane = SwingUtilities.getRootPane(processButton);
- rootPane.setDefaultButton(processButton);
- setVisible(true);
- }
+ JRootPane rootPane = SwingUtilities.getRootPane(processButton);
+ rootPane.setDefaultButton(processButton);
+ setVisible(true);
+ }
- public void setFilterManager(FilterManager filterManager) {
- this.filterManager = filterManager;
- }
+ public void setFilterManager(FilterManager filterManager) {
+ this.filterManager = filterManager;
+ }
- public String sendRequest(Order order) {
- return filterManager.filterRequest(order);
- }
+ public String sendRequest(Order order) {
+ return filterManager.filterRequest(order);
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java
index 214376263..9d5ff1336 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java
@@ -1,24 +1,24 @@
package com.iluwatar.intercepting.filter;
/**
- * Concrete implementation of filter
- * This filter checks for the contact field in which it checks if the input consist of numbers
- * and it also checks if the input follows the length constraint (11 digits)
+ * Concrete implementation of filter This filter checks for the contact field in which it checks if
+ * the input consist of numbers and it also checks if the input follows the length constraint (11
+ * digits)
+ *
* @author joshzambales
*
*/
public class ContactFilter extends AbstractFilter {
-
- @Override
- public String execute(Order order) {
- String result = super.execute(order);
- if (order.getContactNumber() == null
- || order.getContactNumber().isEmpty()
- || order.getContactNumber().matches(".*[^\\d]+.*")
- || order.getContactNumber().length() != 11) {
- return result + "Invalid contact number! ";
- } else {
- return result;
- }
- }
+
+ @Override
+ public String execute(Order order) {
+ String result = super.execute(order);
+ if (order.getContactNumber() == null || order.getContactNumber().isEmpty()
+ || order.getContactNumber().matches(".*[^\\d]+.*")
+ || order.getContactNumber().length() != 11) {
+ return result + "Invalid contact number! ";
+ } else {
+ return result;
+ }
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java
index 129c07cd7..62bc600f3 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java
@@ -1,20 +1,20 @@
package com.iluwatar.intercepting.filter;
/**
- * Concrete implementation of filter
- * This checks for the deposit code
+ * Concrete implementation of filter This checks for the deposit code
+ *
* @author joshzambales
*
*/
public class DepositFilter extends AbstractFilter {
-
- @Override
- public String execute(Order order) {
- String result = super.execute(order);
- if (order.getDepositNumber() == null || order.getDepositNumber().isEmpty()) {
- return result + "Invalid deposit number! ";
- } else {
- return result;
- }
- }
+
+ @Override
+ public String execute(Order order) {
+ String result = super.execute(order);
+ if (order.getDepositNumber() == null || order.getDepositNumber().isEmpty()) {
+ return result + "Invalid deposit number! ";
+ } else {
+ return result;
+ }
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java
index a71be5154..9496bde36 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java
@@ -1,37 +1,40 @@
package com.iluwatar.intercepting.filter;
/**
- * Filters perform certain tasks prior or after execution of
- * request by request handler. In this case, before the request is handled by
- * the target, the request undergoes through each Filter
+ * Filters perform certain tasks prior or after execution of request by request handler. In this
+ * case, before the request is handled by the target, the request undergoes through each Filter
*
* @author joshzambales
*
*/
public interface Filter {
-
- /**
- * Execute order processing filter.
- * @param order
- * @return empty string on success, otherwise error message.
- */
- String execute(Order order);
-
- /**
- * Set next filter in chain after this.
- * @param filter
- */
- void setNext(Filter filter);
-
- /**
- * Get next filter in chain after this.
- * @return
- */
- Filter getNext();
-
- /**
- * Get last filter in the chain.
- * @return
- */
- Filter getLast();
+
+ /**
+ * Execute order processing filter.
+ *
+ * @param order
+ * @return empty string on success, otherwise error message.
+ */
+ String execute(Order order);
+
+ /**
+ * Set next filter in chain after this.
+ *
+ * @param filter
+ */
+ void setNext(Filter filter);
+
+ /**
+ * Get next filter in chain after this.
+ *
+ * @return
+ */
+ Filter getNext();
+
+ /**
+ * Get last filter in the chain.
+ *
+ * @return
+ */
+ Filter getLast();
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java
index e11a58ea0..987678cc7 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java
@@ -1,34 +1,34 @@
- package com.iluwatar.intercepting.filter;
-
-
+package com.iluwatar.intercepting.filter;
+
+
/**
* Filter Chain carries multiple filters and help to execute them in defined order on target.
*
* @author joshzambales
*/
public class FilterChain {
-
- private Filter chain;
-
- private final Target target;
- public FilterChain(Target target) {
- this.target = target;
- }
+ private Filter chain;
- public void addFilter(Filter filter) {
- if (chain == null) {
- chain = filter;
- } else {
- chain.getLast().setNext(filter);
- }
- }
+ private final Target target;
- public String execute(Order order) {
- if (chain != null) {
- return chain.execute(order);
- } else {
- return "RUNNING...";
- }
- }
+ public FilterChain(Target target) {
+ this.target = target;
+ }
+
+ public void addFilter(Filter filter) {
+ if (chain == null) {
+ chain = filter;
+ } else {
+ chain.getLast().setNext(filter);
+ }
+ }
+
+ public String execute(Order order) {
+ if (chain != null) {
+ return chain.execute(order);
+ } else {
+ return "RUNNING...";
+ }
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java
index d15df424a..7cdaab103 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java
@@ -7,18 +7,18 @@ package com.iluwatar.intercepting.filter;
*
*/
public class FilterManager {
-
- private FilterChain filterChain;
- public FilterManager(Target target) {
- filterChain = new FilterChain(target);
- }
+ private FilterChain filterChain;
- public void addFilter(Filter filter) {
- filterChain.addFilter(filter);
- }
+ public FilterManager(Target target) {
+ filterChain = new FilterChain(target);
+ }
- public String filterRequest(Order order) {
- return filterChain.execute(order);
- }
+ public void addFilter(Filter filter) {
+ filterChain.addFilter(filter);
+ }
+
+ public String filterRequest(Order order) {
+ return filterChain.execute(order);
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java
index 201c68bca..a458e475b 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java
@@ -1,21 +1,22 @@
package com.iluwatar.intercepting.filter;
/**
- * Concrete implementation of filter. This filter checks if the input in the Name
- * field is valid. (alphanumeric)
+ * Concrete implementation of filter. This filter checks if the input in the Name field is valid.
+ * (alphanumeric)
*
* @author joshzambales
*
*/
public class NameFilter extends AbstractFilter {
-
- @Override
- public String execute(Order order) {
- String result = super.execute(order);
- if (order.getName() == null || order.getName().isEmpty() || order.getName().matches(".*[^\\w|\\s]+.*")) {
- return result + "Invalid order! ";
- } else {
- return result;
- }
- }
+
+ @Override
+ public String execute(Order order) {
+ String result = super.execute(order);
+ if (order.getName() == null || order.getName().isEmpty()
+ || order.getName().matches(".*[^\\w|\\s]+.*")) {
+ return result + "Invalid order! ";
+ } else {
+ return result;
+ }
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java
index 60bf21f8e..5b30fee35 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java
@@ -6,60 +6,59 @@ package com.iluwatar.intercepting.filter;
*/
public class Order {
- private String name;
- private String contactNumber;
- private String address;
- private String depositNumber;
- private String order;
-
- public Order() {
- }
+ private String name;
+ private String contactNumber;
+ private String address;
+ private String depositNumber;
+ private String order;
- public Order(String name, String contactNumber, String address, String depositNumber, String order) {
- this.name = name;
- this.contactNumber = contactNumber;
- this.address = address;
- this.depositNumber = depositNumber;
- this.order = order;
- }
-
- public String getName() {
- return name;
- }
+ public Order() {}
- public void setName(String name) {
- this.name = name;
- }
+ public Order(String name, String contactNumber, String address, String depositNumber, String order) {
+ this.name = name;
+ this.contactNumber = contactNumber;
+ this.address = address;
+ this.depositNumber = depositNumber;
+ this.order = order;
+ }
- public String getContactNumber() {
- return contactNumber;
- }
+ public String getName() {
+ return name;
+ }
- public void setContactNumber(String contactNumber) {
- this.contactNumber = contactNumber;
- }
+ public void setName(String name) {
+ this.name = name;
+ }
- public String getAddress() {
- return address;
- }
+ public String getContactNumber() {
+ return contactNumber;
+ }
- public void setAddress(String address) {
- this.address = address;
- }
+ public void setContactNumber(String contactNumber) {
+ this.contactNumber = contactNumber;
+ }
- public String getDepositNumber() {
- return depositNumber;
- }
+ public String getAddress() {
+ return address;
+ }
- public void setDepositNumber(String depositNumber) {
- this.depositNumber = depositNumber;
- }
+ public void setAddress(String address) {
+ this.address = address;
+ }
- public String getOrder() {
- return order;
- }
+ public String getDepositNumber() {
+ return depositNumber;
+ }
- public void setOrder(String order) {
- this.order = order;
- }
+ public void setDepositNumber(String depositNumber) {
+ this.depositNumber = depositNumber;
+ }
+
+ public String getOrder() {
+ return order;
+ }
+
+ public void setOrder(String order) {
+ this.order = order;
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java
index cdeaec6e0..724359927 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java
@@ -7,14 +7,14 @@ package com.iluwatar.intercepting.filter;
*
*/
public class OrderFilter extends AbstractFilter {
-
- @Override
- public String execute(Order order) {
- String result = super.execute(order);
- if (order.getOrder() == null || order.getOrder().isEmpty()) {
- return result + "Invalid order! ";
- } else {
- return result;
- }
- }
+
+ @Override
+ public String execute(Order order) {
+ String result = super.execute(order);
+ if (order.getOrder() == null || order.getOrder().isEmpty()) {
+ return result + "Invalid order! ";
+ } else {
+ return result;
+ }
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java
index 6ca456512..cb96cd6e0 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java
@@ -22,57 +22,57 @@ import javax.swing.table.DefaultTableModel;
*/
public class Target extends JFrame {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- private JTable jt;
- private JScrollPane jsp;
- private DefaultTableModel dtm;
- private JButton del;
+ private JTable jt;
+ private JScrollPane jsp;
+ private DefaultTableModel dtm;
+ private JButton del;
- public Target() {
- super("Order System");
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- setSize(640, 480);
- dtm = new DefaultTableModel(new Object[] { "Name", "Contact Number",
- "Address", "Deposit Number", "Order" }, 0);
- jt = new JTable(dtm);
- del = new JButton("Delete");
- setup();
- }
+ public Target() {
+ super("Order System");
+ setDefaultCloseOperation(EXIT_ON_CLOSE);
+ setSize(640, 480);
+ dtm =
+ new DefaultTableModel(new Object[] {"Name", "Contact Number", "Address", "Deposit Number",
+ "Order"}, 0);
+ jt = new JTable(dtm);
+ del = new JButton("Delete");
+ setup();
+ }
- private void setup() {
- setLayout(new BorderLayout());
- JPanel bot = new JPanel();
- add(jt.getTableHeader(), BorderLayout.NORTH);
- bot.setLayout(new BorderLayout());
- bot.add(del, BorderLayout.EAST);
- add(bot, BorderLayout.SOUTH);
- jsp = new JScrollPane(jt);
- jsp.setPreferredSize(new Dimension(500, 250));
- add(jsp, BorderLayout.CENTER);
+ private void setup() {
+ setLayout(new BorderLayout());
+ JPanel bot = new JPanel();
+ add(jt.getTableHeader(), BorderLayout.NORTH);
+ bot.setLayout(new BorderLayout());
+ bot.add(del, BorderLayout.EAST);
+ add(bot, BorderLayout.SOUTH);
+ jsp = new JScrollPane(jt);
+ jsp.setPreferredSize(new Dimension(500, 250));
+ add(jsp, BorderLayout.CENTER);
- del.addActionListener(new DListener());
+ del.addActionListener(new DListener());
- JRootPane rootPane = SwingUtilities.getRootPane(del);
- rootPane.setDefaultButton(del);
- setVisible(true);
- }
+ JRootPane rootPane = SwingUtilities.getRootPane(del);
+ rootPane.setDefaultButton(del);
+ setVisible(true);
+ }
- public void execute(String[] request) {
- dtm.addRow(new Object[] { request[0], request[1], request[2],
- request[3], request[4] });
- }
+ public void execute(String[] request) {
+ dtm.addRow(new Object[] {request[0], request[1], request[2], request[3], request[4]});
+ }
- class DListener implements ActionListener {
- @Override
- public void actionPerformed(ActionEvent e) {
- int temp = jt.getSelectedRow();
- if (temp == -1)
- return;
- int temp2 = jt.getSelectedRowCount();
- for (int i = 0; i < temp2; i++) {
- dtm.removeRow(temp);
- }
- }
- }
+ class DListener implements ActionListener {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ int temp = jt.getSelectedRow();
+ if (temp == -1)
+ return;
+ int temp2 = jt.getSelectedRowCount();
+ for (int i = 0; i < temp2; i++) {
+ dtm.removeRow(temp);
+ }
+ }
+ }
}
diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java
index 9d31127a2..bcdf7c09b 100644
--- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java
+++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.intercepting.filter.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/App.java b/interpreter/src/main/java/com/iluwatar/interpreter/App.java
index 955563915..2f88951f1 100644
--- a/interpreter/src/main/java/com/iluwatar/interpreter/App.java
+++ b/interpreter/src/main/java/com/iluwatar/interpreter/App.java
@@ -4,75 +4,66 @@ import java.util.Stack;
/**
*
- * The Interpreter pattern is a design pattern that specifies how to evaluate sentences
- * in a language. The basic idea is to have a class for each symbol (terminal or nonterminal)
- * in a specialized computer language. The syntax tree of a sentence in the language is an
- * instance of the composite pattern and is used to evaluate (interpret) the sentence for a
- * client.
+ * The Interpreter pattern is a design pattern that specifies how to evaluate sentences in a
+ * language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a
+ * specialized computer language. The syntax tree of a sentence in the language is an instance of
+ * the composite pattern and is used to evaluate (interpret) the sentence for a client.
*
- * In this example we use the Interpreter pattern to break sentences into expressions
- * ({@link Expression}) that can be evaluated and as a whole form the result.
+ * In this example we use the Interpreter pattern to break sentences into expressions (
+ * {@link Expression}) that can be evaluated and as a whole form the result.
*
*/
public class App {
- /**
- *
- * Program entry point.
- *
- * Expressions can be evaluated using prefix, infix or postfix notations
- * This sample uses postfix, where operator comes after the operands
- *
- * @param args command line args
- *
- */
- public static void main(String[] args) {
- String tokenString = "4 3 2 - 1 + *";
- Stack stack = new Stack<>();
+ /**
+ *
+ * Program entry point.
+ *
+ * Expressions can be evaluated using prefix, infix or postfix notations This sample uses postfix,
+ * where operator comes after the operands
+ *
+ * @param args command line args
+ *
+ */
+ public static void main(String[] args) {
+ String tokenString = "4 3 2 - 1 + *";
+ Stack stack = new Stack<>();
- String[] tokenList = tokenString.split(" ");
- for (String s : tokenList) {
- if (isOperator(s)) {
- Expression rightExpression = stack.pop();
- Expression leftExpression = stack.pop();
- System.out
- .println(String.format(
- "popped from stack left: %d right: %d",
- leftExpression.interpret(),
- rightExpression.interpret()));
- Expression operator = getOperatorInstance(s, leftExpression,
- rightExpression);
- System.out.println(String.format("operator: %s", operator));
- int result = operator.interpret();
- NumberExpression resultExpression = new NumberExpression(result);
- stack.push(resultExpression);
- System.out.println(String.format("push result to stack: %d",
- resultExpression.interpret()));
- } else {
- Expression i = new NumberExpression(s);
- stack.push(i);
- System.out.println(String.format("push to stack: %d",
- i.interpret()));
- }
- }
- System.out
- .println(String.format("result: %d", stack.pop().interpret()));
- }
+ String[] tokenList = tokenString.split(" ");
+ for (String s : tokenList) {
+ if (isOperator(s)) {
+ Expression rightExpression = stack.pop();
+ Expression leftExpression = stack.pop();
+ System.out.println(String.format("popped from stack left: %d right: %d",
+ leftExpression.interpret(), rightExpression.interpret()));
+ Expression operator = getOperatorInstance(s, leftExpression, rightExpression);
+ System.out.println(String.format("operator: %s", operator));
+ int result = operator.interpret();
+ NumberExpression resultExpression = new NumberExpression(result);
+ stack.push(resultExpression);
+ System.out.println(String.format("push result to stack: %d", resultExpression.interpret()));
+ } else {
+ Expression i = new NumberExpression(s);
+ stack.push(i);
+ System.out.println(String.format("push to stack: %d", i.interpret()));
+ }
+ }
+ System.out.println(String.format("result: %d", stack.pop().interpret()));
+ }
- public static boolean isOperator(String s) {
- return s.equals("+") || s.equals("-") || s.equals("*");
- }
+ public static boolean isOperator(String s) {
+ return s.equals("+") || s.equals("-") || s.equals("*");
+ }
- public static Expression getOperatorInstance(String s, Expression left,
- Expression right) {
- switch (s) {
- case "+":
- return new PlusExpression(left, right);
- case "-":
- return new MinusExpression(left, right);
- case "*":
- return new MultiplyExpression(left, right);
- }
- return null;
- }
+ public static Expression getOperatorInstance(String s, Expression left, Expression right) {
+ switch (s) {
+ case "+":
+ return new PlusExpression(left, right);
+ case "-":
+ return new MinusExpression(left, right);
+ case "*":
+ return new MultiplyExpression(left, right);
+ }
+ return null;
+ }
}
diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java b/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java
index e70e57f7c..635776115 100644
--- a/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java
+++ b/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java
@@ -7,8 +7,8 @@ package com.iluwatar.interpreter;
*/
public abstract class Expression {
- public abstract int interpret();
+ public abstract int interpret();
- @Override
- public abstract String toString();
+ @Override
+ public abstract String toString();
}
diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java
index d26f977da..d41e75b5a 100644
--- a/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java
+++ b/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java
@@ -7,22 +7,22 @@ package com.iluwatar.interpreter;
*/
public class MinusExpression extends Expression {
- private Expression leftExpression;
- private Expression rightExpression;
+ private Expression leftExpression;
+ private Expression rightExpression;
- public MinusExpression(Expression leftExpression, Expression rightExpression) {
- this.leftExpression = leftExpression;
- this.rightExpression = rightExpression;
- }
+ public MinusExpression(Expression leftExpression, Expression rightExpression) {
+ this.leftExpression = leftExpression;
+ this.rightExpression = rightExpression;
+ }
- @Override
- public int interpret() {
- return leftExpression.interpret() - rightExpression.interpret();
- }
+ @Override
+ public int interpret() {
+ return leftExpression.interpret() - rightExpression.interpret();
+ }
- @Override
- public String toString() {
- return "-";
- }
+ @Override
+ public String toString() {
+ return "-";
+ }
}
diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java
index 9feada7ee..af7c9f9d0 100644
--- a/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java
+++ b/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java
@@ -7,23 +7,22 @@ package com.iluwatar.interpreter;
*/
public class MultiplyExpression extends Expression {
- private Expression leftExpression;
- private Expression rightExpression;
+ private Expression leftExpression;
+ private Expression rightExpression;
- public MultiplyExpression(Expression leftExpression,
- Expression rightExpression) {
- this.leftExpression = leftExpression;
- this.rightExpression = rightExpression;
- }
+ public MultiplyExpression(Expression leftExpression, Expression rightExpression) {
+ this.leftExpression = leftExpression;
+ this.rightExpression = rightExpression;
+ }
- @Override
- public int interpret() {
- return leftExpression.interpret() * rightExpression.interpret();
- }
+ @Override
+ public int interpret() {
+ return leftExpression.interpret() * rightExpression.interpret();
+ }
- @Override
- public String toString() {
- return "*";
- }
+ @Override
+ public String toString() {
+ return "*";
+ }
}
diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java
index 0cf6b034a..4ca4bd589 100644
--- a/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java
+++ b/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java
@@ -7,24 +7,23 @@ package com.iluwatar.interpreter;
*/
public class NumberExpression extends Expression {
- private int number;
+ private int number;
- public NumberExpression(int number) {
- this.number = number;
- }
+ public NumberExpression(int number) {
+ this.number = number;
+ }
- public NumberExpression(String s) {
- this.number = Integer.parseInt(s);
- }
+ public NumberExpression(String s) {
+ this.number = Integer.parseInt(s);
+ }
- @Override
- public int interpret() {
- return number;
- }
-
- @Override
- public String toString() {
- return "number";
- }
+ @Override
+ public int interpret() {
+ return number;
+ }
+ @Override
+ public String toString() {
+ return "number";
+ }
}
diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java
index f244fa946..058199bb2 100644
--- a/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java
+++ b/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java
@@ -7,22 +7,21 @@ package com.iluwatar.interpreter;
*/
public class PlusExpression extends Expression {
- private Expression leftExpression;
- private Expression rightExpression;
+ private Expression leftExpression;
+ private Expression rightExpression;
- public PlusExpression(Expression leftExpression, Expression rightExpression) {
- this.leftExpression = leftExpression;
- this.rightExpression = rightExpression;
- }
+ public PlusExpression(Expression leftExpression, Expression rightExpression) {
+ this.leftExpression = leftExpression;
+ this.rightExpression = rightExpression;
+ }
- @Override
- public int interpret() {
- return leftExpression.interpret() + rightExpression.interpret();
- }
-
- @Override
- public String toString() {
- return "+";
- }
+ @Override
+ public int interpret() {
+ return leftExpression.interpret() + rightExpression.interpret();
+ }
+ @Override
+ public String toString() {
+ return "+";
+ }
}
diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java
index b0e486833..cb7e957c9 100644
--- a/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java
+++ b/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.interpreter.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/iterator/src/main/java/com/iluwatar/iterator/App.java b/iterator/src/main/java/com/iluwatar/iterator/App.java
index b8ecfa42c..c9c5fa521 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/App.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/App.java
@@ -2,48 +2,48 @@ package com.iluwatar.iterator;
/**
*
- * The Iterator pattern is a design pattern in which an iterator is used to
- * traverse a container and access the container's elements. The Iterator pattern
- * decouples algorithms from containers.
+ * The Iterator pattern is a design pattern in which an iterator is used to traverse a container and
+ * access the container's elements. The Iterator pattern decouples algorithms from containers.
*
- * In this example the Iterator ({@link ItemIterator}) adds abstraction layer on
- * top of a collection ({@link TreasureChest}). This way the collection can change
- * its internal implementation without affecting its clients.
+ * In this example the Iterator ({@link ItemIterator}) adds abstraction layer on top of a collection
+ * ({@link TreasureChest}). This way the collection can change its internal implementation without
+ * affecting its clients.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- TreasureChest chest = new TreasureChest();
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ TreasureChest chest = new TreasureChest();
- ItemIterator ringIterator = chest.Iterator(ItemType.RING);
- while (ringIterator.hasNext()) {
- System.out.println(ringIterator.next());
- }
+ ItemIterator ringIterator = chest.Iterator(ItemType.RING);
+ while (ringIterator.hasNext()) {
+ System.out.println(ringIterator.next());
+ }
- System.out.println("----------");
+ System.out.println("----------");
- ItemIterator potionIterator = chest.Iterator(ItemType.POTION);
- while (potionIterator.hasNext()) {
- System.out.println(potionIterator.next());
- }
+ ItemIterator potionIterator = chest.Iterator(ItemType.POTION);
+ while (potionIterator.hasNext()) {
+ System.out.println(potionIterator.next());
+ }
- System.out.println("----------");
+ System.out.println("----------");
- ItemIterator weaponIterator = chest.Iterator(ItemType.WEAPON);
- while (weaponIterator.hasNext()) {
- System.out.println(weaponIterator.next());
- }
+ ItemIterator weaponIterator = chest.Iterator(ItemType.WEAPON);
+ while (weaponIterator.hasNext()) {
+ System.out.println(weaponIterator.next());
+ }
- System.out.println("----------");
+ System.out.println("----------");
- ItemIterator it = chest.Iterator(ItemType.ANY);
- while (it.hasNext()) {
- System.out.println(it.next());
- }
- }
+ ItemIterator it = chest.Iterator(ItemType.ANY);
+ while (it.hasNext()) {
+ System.out.println(it.next());
+ }
+ }
}
diff --git a/iterator/src/main/java/com/iluwatar/iterator/Item.java b/iterator/src/main/java/com/iluwatar/iterator/Item.java
index 4df167c6f..6492fd9ab 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/Item.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/Item.java
@@ -7,24 +7,24 @@ package com.iluwatar.iterator;
*/
public class Item {
- private ItemType type;
- private String name;
+ private ItemType type;
+ private String name;
- public Item(ItemType type, String name) {
- this.setType(type);
- this.name = name;
- }
+ public Item(ItemType type, String name) {
+ this.setType(type);
+ this.name = name;
+ }
- @Override
- public String toString() {
- return name;
- }
+ @Override
+ public String toString() {
+ return name;
+ }
- public ItemType getType() {
- return type;
- }
+ public ItemType getType() {
+ return type;
+ }
- public void setType(ItemType type) {
- this.type = type;
- }
+ public void setType(ItemType type) {
+ this.type = type;
+ }
}
diff --git a/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java b/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java
index 91b5b62c0..3798bbd74 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java
@@ -7,7 +7,7 @@ package com.iluwatar.iterator;
*/
public interface ItemIterator {
- boolean hasNext();
+ boolean hasNext();
- Item next();
+ Item next();
}
diff --git a/iterator/src/main/java/com/iluwatar/iterator/ItemType.java b/iterator/src/main/java/com/iluwatar/iterator/ItemType.java
index 288590c31..3a51c3946 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/ItemType.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/ItemType.java
@@ -7,6 +7,6 @@ package com.iluwatar.iterator;
*/
public enum ItemType {
- ANY, WEAPON, RING, POTION
+ ANY, WEAPON, RING, POTION
}
diff --git a/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java b/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java
index f4e1337bc..02496e33c 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java
@@ -10,30 +10,30 @@ import java.util.List;
*/
public class TreasureChest {
- private List- items;
+ private List
- items;
- public TreasureChest() {
- items = new ArrayList<>();
- items.add(new Item(ItemType.POTION, "Potion of courage"));
- items.add(new Item(ItemType.RING, "Ring of shadows"));
- items.add(new Item(ItemType.POTION, "Potion of wisdom"));
- items.add(new Item(ItemType.POTION, "Potion of blood"));
- items.add(new Item(ItemType.WEAPON, "Sword of silver +1"));
- items.add(new Item(ItemType.POTION, "Potion of rust"));
- items.add(new Item(ItemType.POTION, "Potion of healing"));
- items.add(new Item(ItemType.RING, "Ring of armor"));
- items.add(new Item(ItemType.WEAPON, "Steel halberd"));
- items.add(new Item(ItemType.WEAPON, "Dagger of poison"));
- }
+ public TreasureChest() {
+ items = new ArrayList<>();
+ items.add(new Item(ItemType.POTION, "Potion of courage"));
+ items.add(new Item(ItemType.RING, "Ring of shadows"));
+ items.add(new Item(ItemType.POTION, "Potion of wisdom"));
+ items.add(new Item(ItemType.POTION, "Potion of blood"));
+ items.add(new Item(ItemType.WEAPON, "Sword of silver +1"));
+ items.add(new Item(ItemType.POTION, "Potion of rust"));
+ items.add(new Item(ItemType.POTION, "Potion of healing"));
+ items.add(new Item(ItemType.RING, "Ring of armor"));
+ items.add(new Item(ItemType.WEAPON, "Steel halberd"));
+ items.add(new Item(ItemType.WEAPON, "Dagger of poison"));
+ }
- ItemIterator Iterator(ItemType type) {
- return new TreasureChestItemIterator(this, type);
- }
+ ItemIterator Iterator(ItemType type) {
+ return new TreasureChestItemIterator(this, type);
+ }
- public List
- getItems() {
- ArrayList
- list = new ArrayList<>();
- list.addAll(items);
- return list;
- }
+ public List
- getItems() {
+ ArrayList
- list = new ArrayList<>();
+ list.addAll(items);
+ return list;
+ }
}
diff --git a/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java b/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java
index 1a6daef4e..39c12ab44 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java
@@ -9,46 +9,45 @@ import java.util.List;
*/
public class TreasureChestItemIterator implements ItemIterator {
- private TreasureChest chest;
- private int idx;
- private ItemType type;
+ private TreasureChest chest;
+ private int idx;
+ private ItemType type;
- public TreasureChestItemIterator(TreasureChest chest, ItemType type) {
- this.chest = chest;
- this.type = type;
- this.idx = -1;
- }
+ public TreasureChestItemIterator(TreasureChest chest, ItemType type) {
+ this.chest = chest;
+ this.type = type;
+ this.idx = -1;
+ }
- @Override
- public boolean hasNext() {
- return findNextIdx() != -1;
- }
+ @Override
+ public boolean hasNext() {
+ return findNextIdx() != -1;
+ }
- @Override
- public Item next() {
- idx = findNextIdx();
- if (idx != -1) {
- return chest.getItems().get(idx);
- }
- return null;
- }
+ @Override
+ public Item next() {
+ idx = findNextIdx();
+ if (idx != -1) {
+ return chest.getItems().get(idx);
+ }
+ return null;
+ }
- private int findNextIdx() {
+ private int findNextIdx() {
- List
- items = chest.getItems();
- boolean found = false;
- int tempIdx = idx;
- while (!found) {
- tempIdx++;
- if (tempIdx >= items.size()) {
- tempIdx = -1;
- break;
- }
- if (type.equals(ItemType.ANY)
- || items.get(tempIdx).getType().equals(type)) {
- break;
- }
- }
- return tempIdx;
- }
+ List
- items = chest.getItems();
+ boolean found = false;
+ int tempIdx = idx;
+ while (!found) {
+ tempIdx++;
+ if (tempIdx >= items.size()) {
+ tempIdx = -1;
+ break;
+ }
+ if (type.equals(ItemType.ANY) || items.get(tempIdx).getType().equals(type)) {
+ break;
+ }
+ }
+ return tempIdx;
+ }
}
diff --git a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java b/iterator/src/test/java/com/iluwatar/iterator/AppTest.java
index 1c1d65e34..b6198f5c5 100644
--- a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java
+++ b/iterator/src/test/java/com/iluwatar/iterator/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.iterator.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/layers/src/main/java/com/iluwatar/layers/App.java b/layers/src/main/java/com/iluwatar/layers/App.java
index bac946265..d175553f7 100644
--- a/layers/src/main/java/com/iluwatar/layers/App.java
+++ b/layers/src/main/java/com/iluwatar/layers/App.java
@@ -4,32 +4,31 @@ import java.util.Arrays;
/**
*
- * Layers is an architectural style where software responsibilities are
- * divided among the different layers of the application.
+ * Layers is an architectural style where software responsibilities are divided among the different
+ * layers of the application.
*
- * This example demonstrates a traditional 3-layer architecture consisting of data access
- * layer, business layer and presentation layer.
+ * This example demonstrates a traditional 3-layer architecture consisting of data access layer,
+ * business layer and presentation layer.
*
- * The data access layer is formed of Spring Data repositories CakeDao
, CakeToppingDao
and
- * CakeLayerDao
. The repositories can be used for CRUD operations on cakes, cake toppings
- * and cake layers respectively.
+ * The data access layer is formed of Spring Data repositories CakeDao
,
+ * CakeToppingDao
and CakeLayerDao
. The repositories can be used for CRUD
+ * operations on cakes, cake toppings and cake layers respectively.
*
- * The business layer is built on top of the data access layer. CakeBakingService
offers
- * methods to retrieve available cake toppings and cake layers and baked cakes. Also the
+ * The business layer is built on top of the data access layer. CakeBakingService
+ * offers methods to retrieve available cake toppings and cake layers and baked cakes. Also the
* service is used to create new cakes out of cake toppings and cake layers.
*
- * The presentation layer is built on the business layer and in this example it simply lists
- * the cakes that have been baked.
+ * The presentation layer is built on the business layer and in this example it simply lists the
+ * cakes that have been baked.
*
- * We have applied so called strict layering which means that the layers can only access
- * the classes directly beneath them. This leads the solution to create an additional set of
- * DTOs (CakeInfo
, CakeToppingInfo
, CakeLayerInfo
)
- * to translate data between layers. In other words, CakeBakingService
cannot
- * return entities (Cake
, CakeTopping
, CakeLayer
)
- * directly since these reside on data access layer but instead translates these into business
- * layer DTOs (CakeInfo
, CakeToppingInfo
, CakeLayerInfo
)
- * and returns them instead. This way the presentation layer does not have any knowledge of
- * other layers than the business layer and thus is not affected by changes to them.
+ * We have applied so called strict layering which means that the layers can only access the classes
+ * directly beneath them. This leads the solution to create an additional set of DTOs (
+ * CakeInfo
, CakeToppingInfo
, CakeLayerInfo
) to translate
+ * data between layers. In other words, CakeBakingService
cannot return entities (
+ * Cake
, CakeTopping
, CakeLayer
) directly since these reside
+ * on data access layer but instead translates these into business layer DTOs (CakeInfo
, CakeToppingInfo
, CakeLayerInfo
) and returns them instead. This way
+ * the presentation layer does not have any knowledge of other layers than the business layer and
+ * thus is not affected by changes to them.
*
* @see Cake
* @see CakeTopping
@@ -45,52 +44,55 @@ import java.util.Arrays;
*/
public class App {
- private static CakeBakingService cakeBakingService = new CakeBakingServiceImpl();
-
- /**
- * Application entry point
- * @param args Command line parameters
- */
- public static void main(String[] args) {
-
- // initialize example data
- initializeData(cakeBakingService);
-
- // create view and render it
- CakeViewImpl cakeView = new CakeViewImpl(cakeBakingService);
- cakeView.render();
- }
-
- /**
- * Initializes the example data
- * @param cakeBakingService
- */
- private static void initializeData(CakeBakingService cakeBakingService) {
- cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200));
- cakeBakingService.saveNewLayer(new CakeLayerInfo("banana", 900));
- cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950));
- cakeBakingService.saveNewLayer(new CakeLayerInfo("lemon", 950));
- cakeBakingService.saveNewLayer(new CakeLayerInfo("vanilla", 950));
- cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950));
-
- cakeBakingService.saveNewTopping(new CakeToppingInfo("candies", 350));
- cakeBakingService.saveNewTopping(new CakeToppingInfo("cherry", 350));
+ private static CakeBakingService cakeBakingService = new CakeBakingServiceImpl();
- CakeInfo cake1 = new CakeInfo(new CakeToppingInfo("candies", 0),
- Arrays.asList(new CakeLayerInfo("chocolate", 0), new CakeLayerInfo("banana", 0),
- new CakeLayerInfo("strawberry", 0)));
- try {
- cakeBakingService.bakeNewCake(cake1);
- } catch (CakeBakingException e) {
- e.printStackTrace();
- }
- CakeInfo cake2 = new CakeInfo(new CakeToppingInfo("cherry", 0),
- Arrays.asList(new CakeLayerInfo("vanilla", 0), new CakeLayerInfo("lemon", 0),
- new CakeLayerInfo("strawberry", 0)));
- try {
- cakeBakingService.bakeNewCake(cake2);
- } catch (CakeBakingException e) {
- e.printStackTrace();
- }
- }
+ /**
+ * Application entry point
+ *
+ * @param args Command line parameters
+ */
+ public static void main(String[] args) {
+
+ // initialize example data
+ initializeData(cakeBakingService);
+
+ // create view and render it
+ CakeViewImpl cakeView = new CakeViewImpl(cakeBakingService);
+ cakeView.render();
+ }
+
+ /**
+ * Initializes the example data
+ *
+ * @param cakeBakingService
+ */
+ private static void initializeData(CakeBakingService cakeBakingService) {
+ cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200));
+ cakeBakingService.saveNewLayer(new CakeLayerInfo("banana", 900));
+ cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950));
+ cakeBakingService.saveNewLayer(new CakeLayerInfo("lemon", 950));
+ cakeBakingService.saveNewLayer(new CakeLayerInfo("vanilla", 950));
+ cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950));
+
+ cakeBakingService.saveNewTopping(new CakeToppingInfo("candies", 350));
+ cakeBakingService.saveNewTopping(new CakeToppingInfo("cherry", 350));
+
+ CakeInfo cake1 =
+ new CakeInfo(new CakeToppingInfo("candies", 0), Arrays.asList(new CakeLayerInfo(
+ "chocolate", 0), new CakeLayerInfo("banana", 0), new CakeLayerInfo("strawberry", 0)));
+ try {
+ cakeBakingService.bakeNewCake(cake1);
+ } catch (CakeBakingException e) {
+ e.printStackTrace();
+ }
+ CakeInfo cake2 =
+ new CakeInfo(new CakeToppingInfo("cherry", 0), Arrays.asList(
+ new CakeLayerInfo("vanilla", 0), new CakeLayerInfo("lemon", 0), new CakeLayerInfo(
+ "strawberry", 0)));
+ try {
+ cakeBakingService.bakeNewCake(cake2);
+ } catch (CakeBakingException e) {
+ e.printStackTrace();
+ }
+ }
}
diff --git a/layers/src/main/java/com/iluwatar/layers/Cake.java b/layers/src/main/java/com/iluwatar/layers/Cake.java
index 193ba5e3f..b251576bf 100644
--- a/layers/src/main/java/com/iluwatar/layers/Cake.java
+++ b/layers/src/main/java/com/iluwatar/layers/Cake.java
@@ -19,50 +19,50 @@ import javax.persistence.OneToOne;
@Entity
public class Cake {
- @Id
- @GeneratedValue
- private Long id;
+ @Id
+ @GeneratedValue
+ private Long id;
- @OneToOne(cascade=CascadeType.REMOVE)
- private CakeTopping topping;
-
- @OneToMany(cascade=CascadeType.REMOVE, fetch=FetchType.EAGER)
- private Set layers;
-
- public Cake() {
- setLayers(new HashSet<>());
- }
+ @OneToOne(cascade = CascadeType.REMOVE)
+ private CakeTopping topping;
- public Long getId() {
- return id;
- }
+ @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER)
+ private Set layers;
- public void setId(Long id) {
- this.id = id;
- }
+ public Cake() {
+ setLayers(new HashSet<>());
+ }
- public CakeTopping getTopping() {
- return topping;
- }
+ public Long getId() {
+ return id;
+ }
- public void setTopping(CakeTopping topping) {
- this.topping = topping;
- }
+ public void setId(Long id) {
+ this.id = id;
+ }
- public Set getLayers() {
- return layers;
- }
+ public CakeTopping getTopping() {
+ return topping;
+ }
- public void setLayers(Set layers) {
- this.layers = layers;
- }
-
- public void addLayer(CakeLayer layer) {
- this.layers.add(layer);
- }
-
- @Override
- public String toString() {
- return String.format("id=%s topping=%s layers=%s", id, topping, layers.toString());
- }
+ public void setTopping(CakeTopping topping) {
+ this.topping = topping;
+ }
+
+ public Set getLayers() {
+ return layers;
+ }
+
+ public void setLayers(Set layers) {
+ this.layers = layers;
+ }
+
+ public void addLayer(CakeLayer layer) {
+ this.layers.add(layer);
+ }
+
+ @Override
+ public String toString() {
+ return String.format("id=%s topping=%s layers=%s", id, topping, layers.toString());
+ }
}
diff --git a/layers/src/main/java/com/iluwatar/layers/CakeBakingException.java b/layers/src/main/java/com/iluwatar/layers/CakeBakingException.java
index 0a44d56f9..a61b65b81 100644
--- a/layers/src/main/java/com/iluwatar/layers/CakeBakingException.java
+++ b/layers/src/main/java/com/iluwatar/layers/CakeBakingException.java
@@ -6,13 +6,12 @@ package com.iluwatar.layers;
*
*/
public class CakeBakingException extends Exception {
-
- private static final long serialVersionUID = 1L;
- public CakeBakingException() {
- }
+ private static final long serialVersionUID = 1L;
- public CakeBakingException(String message) {
- super(message);
- }
+ public CakeBakingException() {}
+
+ public CakeBakingException(String message) {
+ super(message);
+ }
}
diff --git a/layers/src/main/java/com/iluwatar/layers/CakeBakingService.java b/layers/src/main/java/com/iluwatar/layers/CakeBakingService.java
index fec16b494..80bd3438b 100644
--- a/layers/src/main/java/com/iluwatar/layers/CakeBakingService.java
+++ b/layers/src/main/java/com/iluwatar/layers/CakeBakingService.java
@@ -8,41 +8,47 @@ import java.util.List;
*
*/
public interface CakeBakingService {
-
- /**
- * Bakes new cake according to parameters
- * @param cakeInfo
- * @throws CakeBakingException
- */
- void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException;
-
- /**
- * Get all cakes
- * @return
- */
- List getAllCakes();
- /**
- * Store new cake topping
- * @param toppingInfo
- */
- void saveNewTopping(CakeToppingInfo toppingInfo);
+ /**
+ * Bakes new cake according to parameters
+ *
+ * @param cakeInfo
+ * @throws CakeBakingException
+ */
+ void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException;
- /**
- * Get available cake toppings
- * @return
- */
- List getAvailableToppings();
-
- /**
- * Add new cake layer
- * @param layerInfo
- */
- void saveNewLayer(CakeLayerInfo layerInfo);
-
- /**
- * Get available cake layers
- * @return
- */
- List getAvailableLayers();
+ /**
+ * Get all cakes
+ *
+ * @return
+ */
+ List getAllCakes();
+
+ /**
+ * Store new cake topping
+ *
+ * @param toppingInfo
+ */
+ void saveNewTopping(CakeToppingInfo toppingInfo);
+
+ /**
+ * Get available cake toppings
+ *
+ * @return
+ */
+ List getAvailableToppings();
+
+ /**
+ * Add new cake layer
+ *
+ * @param layerInfo
+ */
+ void saveNewLayer(CakeLayerInfo layerInfo);
+
+ /**
+ * Get available cake layers
+ *
+ * @return
+ */
+ List getAvailableLayers();
}
diff --git a/layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java b/layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java
index 7e5e3dcff..a519ec2ce 100644
--- a/layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java
+++ b/layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java
@@ -22,128 +22,132 @@ import org.springframework.transaction.annotation.Transactional;
@Transactional
public class CakeBakingServiceImpl implements CakeBakingService {
- private AbstractApplicationContext context;
+ private AbstractApplicationContext context;
- public CakeBakingServiceImpl() {
- this.context = new ClassPathXmlApplicationContext("applicationContext.xml");
- }
-
- @Override
- public void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException {
- List allToppings = getAvailableToppings();
- List matchingToppings = allToppings.stream()
- .filter((t) -> t.name.equals(cakeInfo.cakeToppingInfo.name)).collect(Collectors.toList());
- if (matchingToppings.isEmpty()) {
- throw new CakeBakingException(String.format("Topping %s is not available", cakeInfo.cakeToppingInfo.name));
- }
- List allLayers = getAvailableLayerEntities();
- Set foundLayers = new HashSet<>();
- for (CakeLayerInfo info: cakeInfo.cakeLayerInfos) {
- Optional found = allLayers.stream().filter((layer) -> layer.getName().equals(info.name)).findFirst();
- if (!found.isPresent()) {
- throw new CakeBakingException(String.format("Layer %s is not available", info.name));
- } else {
- foundLayers.add(found.get());
- }
- }
- CakeToppingDao toppingBean = context.getBean(CakeToppingDao.class);
- CakeTopping topping = toppingBean.findOne(matchingToppings.iterator().next().id.get());
- CakeDao cakeBean = context.getBean(CakeDao.class);
- Cake cake = new Cake();
- cake.setTopping(topping);
- cake.setLayers(foundLayers);
- cakeBean.save(cake);
- topping.setCake(cake);
- toppingBean.save(topping);
- CakeLayerDao layerBean = context.getBean(CakeLayerDao.class);
- for (CakeLayer layer: foundLayers) {
- layer.setCake(cake);
- layerBean.save(layer);
- }
- }
+ public CakeBakingServiceImpl() {
+ this.context = new ClassPathXmlApplicationContext("applicationContext.xml");
+ }
- @Override
- public void saveNewTopping(CakeToppingInfo toppingInfo) {
- CakeToppingDao bean = context.getBean(CakeToppingDao.class);
- bean.save(new CakeTopping(toppingInfo.name, toppingInfo.calories));
- }
+ @Override
+ public void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException {
+ List allToppings = getAvailableToppings();
+ List matchingToppings =
+ allToppings.stream().filter((t) -> t.name.equals(cakeInfo.cakeToppingInfo.name))
+ .collect(Collectors.toList());
+ if (matchingToppings.isEmpty()) {
+ throw new CakeBakingException(String.format("Topping %s is not available",
+ cakeInfo.cakeToppingInfo.name));
+ }
+ List allLayers = getAvailableLayerEntities();
+ Set foundLayers = new HashSet<>();
+ for (CakeLayerInfo info : cakeInfo.cakeLayerInfos) {
+ Optional found =
+ allLayers.stream().filter((layer) -> layer.getName().equals(info.name)).findFirst();
+ if (!found.isPresent()) {
+ throw new CakeBakingException(String.format("Layer %s is not available", info.name));
+ } else {
+ foundLayers.add(found.get());
+ }
+ }
+ CakeToppingDao toppingBean = context.getBean(CakeToppingDao.class);
+ CakeTopping topping = toppingBean.findOne(matchingToppings.iterator().next().id.get());
+ CakeDao cakeBean = context.getBean(CakeDao.class);
+ Cake cake = new Cake();
+ cake.setTopping(topping);
+ cake.setLayers(foundLayers);
+ cakeBean.save(cake);
+ topping.setCake(cake);
+ toppingBean.save(topping);
+ CakeLayerDao layerBean = context.getBean(CakeLayerDao.class);
+ for (CakeLayer layer : foundLayers) {
+ layer.setCake(cake);
+ layerBean.save(layer);
+ }
+ }
- @Override
- public void saveNewLayer(CakeLayerInfo layerInfo) {
- CakeLayerDao bean = context.getBean(CakeLayerDao.class);
- bean.save(new CakeLayer(layerInfo.name, layerInfo.calories));
- }
+ @Override
+ public void saveNewTopping(CakeToppingInfo toppingInfo) {
+ CakeToppingDao bean = context.getBean(CakeToppingDao.class);
+ bean.save(new CakeTopping(toppingInfo.name, toppingInfo.calories));
+ }
- private List getAvailableToppingEntities() {
- CakeToppingDao bean = context.getBean(CakeToppingDao.class);
- List result = new ArrayList<>();
- Iterator iterator = bean.findAll().iterator();
- while (iterator.hasNext()) {
- CakeTopping topping = iterator.next();
- if (topping.getCake() == null) {
- result.add(topping);
- }
- }
- return result;
- }
-
- @Override
- public List getAvailableToppings() {
- CakeToppingDao bean = context.getBean(CakeToppingDao.class);
- List result = new ArrayList<>();
- Iterator iterator = bean.findAll().iterator();
- while (iterator.hasNext()) {
- CakeTopping next = iterator.next();
- if (next.getCake() == null) {
- result.add(new CakeToppingInfo(next.getId(), next.getName(), next.getCalories()));
- }
- }
- return result;
- }
+ @Override
+ public void saveNewLayer(CakeLayerInfo layerInfo) {
+ CakeLayerDao bean = context.getBean(CakeLayerDao.class);
+ bean.save(new CakeLayer(layerInfo.name, layerInfo.calories));
+ }
- private List getAvailableLayerEntities() {
- CakeLayerDao bean = context.getBean(CakeLayerDao.class);
- List result = new ArrayList<>();
- Iterator iterator = bean.findAll().iterator();
- while (iterator.hasNext()) {
- CakeLayer next = iterator.next();
- if (next.getCake() == null) {
- result.add(next);
- }
- }
- return result;
- }
-
- @Override
- public List getAvailableLayers() {
- CakeLayerDao bean = context.getBean(CakeLayerDao.class);
- List result = new ArrayList<>();
- Iterator iterator = bean.findAll().iterator();
- while (iterator.hasNext()) {
- CakeLayer next = iterator.next();
- if (next.getCake() == null) {
- result.add(new CakeLayerInfo(next.getId(), next.getName(), next.getCalories()));
- }
- }
- return result;
- }
+ private List getAvailableToppingEntities() {
+ CakeToppingDao bean = context.getBean(CakeToppingDao.class);
+ List result = new ArrayList<>();
+ Iterator iterator = bean.findAll().iterator();
+ while (iterator.hasNext()) {
+ CakeTopping topping = iterator.next();
+ if (topping.getCake() == null) {
+ result.add(topping);
+ }
+ }
+ return result;
+ }
- @Override
- public List getAllCakes() {
- CakeDao cakeBean = context.getBean(CakeDao.class);
- List result = new ArrayList<>();
- Iterator iterator = cakeBean.findAll().iterator();
- while (iterator.hasNext()) {
- Cake cake = iterator.next();
- CakeToppingInfo cakeToppingInfo = new CakeToppingInfo(cake.getTopping().getId(),
- cake.getTopping().getName(), cake.getTopping().getCalories());
- ArrayList cakeLayerInfos = new ArrayList();
- for (CakeLayer layer: cake.getLayers()) {
- cakeLayerInfos.add(new CakeLayerInfo(layer.getId(), layer.getName(), layer.getCalories()));
- }
- CakeInfo cakeInfo = new CakeInfo(cake.getId(), cakeToppingInfo, cakeLayerInfos);
- result.add(cakeInfo);
- }
- return result;
- }
+ @Override
+ public List getAvailableToppings() {
+ CakeToppingDao bean = context.getBean(CakeToppingDao.class);
+ List result = new ArrayList<>();
+ Iterator iterator = bean.findAll().iterator();
+ while (iterator.hasNext()) {
+ CakeTopping next = iterator.next();
+ if (next.getCake() == null) {
+ result.add(new CakeToppingInfo(next.getId(), next.getName(), next.getCalories()));
+ }
+ }
+ return result;
+ }
+
+ private List getAvailableLayerEntities() {
+ CakeLayerDao bean = context.getBean(CakeLayerDao.class);
+ List result = new ArrayList<>();
+ Iterator iterator = bean.findAll().iterator();
+ while (iterator.hasNext()) {
+ CakeLayer next = iterator.next();
+ if (next.getCake() == null) {
+ result.add(next);
+ }
+ }
+ return result;
+ }
+
+ @Override
+ public List getAvailableLayers() {
+ CakeLayerDao bean = context.getBean(CakeLayerDao.class);
+ List result = new ArrayList<>();
+ Iterator iterator = bean.findAll().iterator();
+ while (iterator.hasNext()) {
+ CakeLayer next = iterator.next();
+ if (next.getCake() == null) {
+ result.add(new CakeLayerInfo(next.getId(), next.getName(), next.getCalories()));
+ }
+ }
+ return result;
+ }
+
+ @Override
+ public List getAllCakes() {
+ CakeDao cakeBean = context.getBean(CakeDao.class);
+ List result = new ArrayList<>();
+ Iterator iterator = cakeBean.findAll().iterator();
+ while (iterator.hasNext()) {
+ Cake cake = iterator.next();
+ CakeToppingInfo cakeToppingInfo =
+ new CakeToppingInfo(cake.getTopping().getId(), cake.getTopping().getName(), cake
+ .getTopping().getCalories());
+ ArrayList cakeLayerInfos = new ArrayList();
+ for (CakeLayer layer : cake.getLayers()) {
+ cakeLayerInfos.add(new CakeLayerInfo(layer.getId(), layer.getName(), layer.getCalories()));
+ }
+ CakeInfo cakeInfo = new CakeInfo(cake.getId(), cakeToppingInfo, cakeLayerInfos);
+ result.add(cakeInfo);
+ }
+ return result;
+ }
}
diff --git a/layers/src/main/java/com/iluwatar/layers/CakeInfo.java b/layers/src/main/java/com/iluwatar/layers/CakeInfo.java
index 335ce5f4f..f60ee9a14 100644
--- a/layers/src/main/java/com/iluwatar/layers/CakeInfo.java
+++ b/layers/src/main/java/com/iluwatar/layers/CakeInfo.java
@@ -10,31 +10,31 @@ import java.util.Optional;
*/
public class CakeInfo {
- public final Optional id;
- public final CakeToppingInfo cakeToppingInfo;
- public final List cakeLayerInfos;
+ public final Optional id;
+ public final CakeToppingInfo cakeToppingInfo;
+ public final List cakeLayerInfos;
- public CakeInfo(Long id, CakeToppingInfo cakeToppingInfo, List cakeLayerInfos) {
- this.id = Optional.of(id);
- this.cakeToppingInfo = cakeToppingInfo;
- this.cakeLayerInfos = cakeLayerInfos;
- }
-
- public CakeInfo(CakeToppingInfo cakeToppingInfo, List cakeLayerInfos) {
- this.id = Optional.empty();
- this.cakeToppingInfo = cakeToppingInfo;
- this.cakeLayerInfos = cakeLayerInfos;
- }
-
- public int calculateTotalCalories() {
- int total = cakeToppingInfo != null ? cakeToppingInfo.calories : 0;
- total += cakeLayerInfos.stream().mapToInt(c -> c.calories).sum();
- return total;
- }
-
- @Override
- public String toString() {
- return String.format("CakeInfo id=%d topping=%s layers=%s totalCalories=%d", id.get(), cakeToppingInfo,
- cakeLayerInfos, calculateTotalCalories());
- }
+ public CakeInfo(Long id, CakeToppingInfo cakeToppingInfo, List cakeLayerInfos) {
+ this.id = Optional.of(id);
+ this.cakeToppingInfo = cakeToppingInfo;
+ this.cakeLayerInfos = cakeLayerInfos;
+ }
+
+ public CakeInfo(CakeToppingInfo cakeToppingInfo, List cakeLayerInfos) {
+ this.id = Optional.empty();
+ this.cakeToppingInfo = cakeToppingInfo;
+ this.cakeLayerInfos = cakeLayerInfos;
+ }
+
+ public int calculateTotalCalories() {
+ int total = cakeToppingInfo != null ? cakeToppingInfo.calories : 0;
+ total += cakeLayerInfos.stream().mapToInt(c -> c.calories).sum();
+ return total;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("CakeInfo id=%d topping=%s layers=%s totalCalories=%d", id.get(),
+ cakeToppingInfo, cakeLayerInfos, calculateTotalCalories());
+ }
}
diff --git a/layers/src/main/java/com/iluwatar/layers/CakeLayer.java b/layers/src/main/java/com/iluwatar/layers/CakeLayer.java
index 2f8649c18..7cbb55e28 100644
--- a/layers/src/main/java/com/iluwatar/layers/CakeLayer.java
+++ b/layers/src/main/java/com/iluwatar/layers/CakeLayer.java
@@ -14,59 +14,58 @@ import javax.persistence.ManyToOne;
@Entity
public class CakeLayer {
- @Id
- @GeneratedValue
- private Long id;
+ @Id
+ @GeneratedValue
+ private Long id;
- private String name;
+ private String name;
- private int calories;
-
- @ManyToOne(cascade = CascadeType.ALL)
- private Cake cake;
+ private int calories;
- public CakeLayer() {
- }
+ @ManyToOne(cascade = CascadeType.ALL)
+ private Cake cake;
- public CakeLayer(String name, int calories) {
- this.setName(name);
- this.setCalories(calories);
- }
+ public CakeLayer() {}
- public Long getId() {
- return id;
- }
+ public CakeLayer(String name, int calories) {
+ this.setName(name);
+ this.setCalories(calories);
+ }
- public void setId(Long id) {
- this.id = id;
- }
+ public Long getId() {
+ return id;
+ }
- public String getName() {
- return name;
- }
+ public void setId(Long id) {
+ this.id = id;
+ }
- public void setName(String name) {
- this.name = name;
- }
+ public String getName() {
+ return name;
+ }
- public int getCalories() {
- return calories;
- }
+ public void setName(String name) {
+ this.name = name;
+ }
- public void setCalories(int calories) {
- this.calories = calories;
- }
-
- @Override
- public String toString() {
- return String.format("id=%s name=%s calories=%d", id, name, calories);
- }
+ public int getCalories() {
+ return calories;
+ }
- public Cake getCake() {
- return cake;
- }
+ public void setCalories(int calories) {
+ this.calories = calories;
+ }
- public void setCake(Cake cake) {
- this.cake = cake;
- }
+ @Override
+ public String toString() {
+ return String.format("id=%s name=%s calories=%d", id, name, calories);
+ }
+
+ public Cake getCake() {
+ return cake;
+ }
+
+ public void setCake(Cake cake) {
+ this.cake = cake;
+ }
}
diff --git a/layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java b/layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java
index 9aa7ff7f6..3dff379da 100644
--- a/layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java
+++ b/layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java
@@ -9,24 +9,24 @@ import java.util.Optional;
*/
public class CakeLayerInfo {
- public final Optional id;
- public final String name;
- public final int calories;
+ public final Optional id;
+ public final String name;
+ public final int calories;
- public CakeLayerInfo(Long id, String name, int calories) {
- this.id = Optional.of(id);
- this.name = name;
- this.calories = calories;
- }
-
- public CakeLayerInfo(String name, int calories) {
- this.id = Optional.empty();
- this.name = name;
- this.calories = calories;
- }
-
- @Override
- public String toString() {
- return String.format("CakeLayerInfo id=%d name=%s calories=%d", id.get(), name, calories);
- }
+ public CakeLayerInfo(Long id, String name, int calories) {
+ this.id = Optional.of(id);
+ this.name = name;
+ this.calories = calories;
+ }
+
+ public CakeLayerInfo(String name, int calories) {
+ this.id = Optional.empty();
+ this.name = name;
+ this.calories = calories;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("CakeLayerInfo id=%d name=%s calories=%d", id.get(), name, calories);
+ }
}
diff --git a/layers/src/main/java/com/iluwatar/layers/CakeTopping.java b/layers/src/main/java/com/iluwatar/layers/CakeTopping.java
index f0e30997a..6dc9c45fc 100644
--- a/layers/src/main/java/com/iluwatar/layers/CakeTopping.java
+++ b/layers/src/main/java/com/iluwatar/layers/CakeTopping.java
@@ -14,59 +14,58 @@ import javax.persistence.OneToOne;
@Entity
public class CakeTopping {
- @Id
- @GeneratedValue
- private Long id;
-
- private String name;
-
- private int calories;
-
- @OneToOne(cascade = CascadeType.ALL)
- private Cake cake;
-
- public CakeTopping() {
- }
-
- public CakeTopping(String name, int calories) {
- this.setName(name);
- this.setCalories(calories);
- }
+ @Id
+ @GeneratedValue
+ private Long id;
- public Long getId() {
- return id;
- }
+ private String name;
- public void setId(Long id) {
- this.id = id;
- }
+ private int calories;
- public String getName() {
- return name;
- }
+ @OneToOne(cascade = CascadeType.ALL)
+ private Cake cake;
- public void setName(String name) {
- this.name = name;
- }
+ public CakeTopping() {}
- public int getCalories() {
- return calories;
- }
+ public CakeTopping(String name, int calories) {
+ this.setName(name);
+ this.setCalories(calories);
+ }
- public void setCalories(int calories) {
- this.calories = calories;
- }
-
- @Override
- public String toString() {
- return String.format("id=%s name=%s calories=%d", name, calories);
- }
+ public Long getId() {
+ return id;
+ }
- public Cake getCake() {
- return cake;
- }
+ public void setId(Long id) {
+ this.id = id;
+ }
- public void setCake(Cake cake) {
- this.cake = cake;
- }
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public int getCalories() {
+ return calories;
+ }
+
+ public void setCalories(int calories) {
+ this.calories = calories;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("id=%s name=%s calories=%d", name, calories);
+ }
+
+ public Cake getCake() {
+ return cake;
+ }
+
+ public void setCake(Cake cake) {
+ this.cake = cake;
+ }
}
diff --git a/layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java b/layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java
index 152b0ff85..4e432ec44 100644
--- a/layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java
+++ b/layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java
@@ -9,24 +9,24 @@ import java.util.Optional;
*/
public class CakeToppingInfo {
- public final Optional id;
- public final String name;
- public final int calories;
+ public final Optional id;
+ public final String name;
+ public final int calories;
- public CakeToppingInfo(Long id, String name, int calories) {
- this.id = Optional.of(id);
- this.name = name;
- this.calories = calories;
- }
-
- public CakeToppingInfo(String name, int calories) {
- this.id = Optional.empty();
- this.name = name;
- this.calories = calories;
- }
-
- @Override
- public String toString() {
- return String.format("CakeToppingInfo id=%d name=%s calories=%d", id.get(), name, calories);
- }
+ public CakeToppingInfo(Long id, String name, int calories) {
+ this.id = Optional.of(id);
+ this.name = name;
+ this.calories = calories;
+ }
+
+ public CakeToppingInfo(String name, int calories) {
+ this.id = Optional.empty();
+ this.name = name;
+ this.calories = calories;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("CakeToppingInfo id=%d name=%s calories=%d", id.get(), name, calories);
+ }
}
diff --git a/layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java b/layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java
index 5fed15c3a..3a465b2b6 100644
--- a/layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java
+++ b/layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java
@@ -7,13 +7,13 @@ package com.iluwatar.layers;
*/
public class CakeViewImpl implements View {
- private CakeBakingService cakeBakingService;
+ private CakeBakingService cakeBakingService;
- public CakeViewImpl(CakeBakingService cakeBakingService) {
- this.cakeBakingService = cakeBakingService;
- }
-
- public void render() {
- cakeBakingService.getAllCakes().stream().forEach((cake) -> System.out.println(cake));
- }
+ public CakeViewImpl(CakeBakingService cakeBakingService) {
+ this.cakeBakingService = cakeBakingService;
+ }
+
+ public void render() {
+ cakeBakingService.getAllCakes().stream().forEach((cake) -> System.out.println(cake));
+ }
}
diff --git a/layers/src/main/java/com/iluwatar/layers/View.java b/layers/src/main/java/com/iluwatar/layers/View.java
index 123d4ecbf..be2187e4d 100644
--- a/layers/src/main/java/com/iluwatar/layers/View.java
+++ b/layers/src/main/java/com/iluwatar/layers/View.java
@@ -7,6 +7,6 @@ package com.iluwatar.layers;
*/
public interface View {
- void render();
-
+ void render();
+
}
diff --git a/layers/src/test/java/com/iluwatar/layers/AppTest.java b/layers/src/test/java/com/iluwatar/layers/AppTest.java
index e55ab4f84..7db3f6ecd 100644
--- a/layers/src/test/java/com/iluwatar/layers/AppTest.java
+++ b/layers/src/test/java/com/iluwatar/layers/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.layers.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java
index db09c781b..14708f0e9 100644
--- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java
+++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java
@@ -4,34 +4,33 @@ package com.iluwatar.lazy.loading;
*
* Lazy loading idiom defers object creation until needed.
*
- * This example shows different implementations of the pattern
- * with increasing sophistication.
+ * This example shows different implementations of the pattern with increasing sophistication.
*
* Additional information and lazy loading flavours are described in
* http://martinfowler.com/eaaCatalog/lazyLoad.html
*
*/
-public class App
-{
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
-
- // Simple lazy loader - not thread safe
- HolderNaive holderNaive = new HolderNaive();
- Heavy heavy = holderNaive.getHeavy();
- System.out.println("heavy=" + heavy);
-
- // Thread safe lazy loader, but with heavy synchronization on each access
- HolderThreadSafe holderThreadSafe = new HolderThreadSafe();
- Heavy another = holderThreadSafe.getHeavy();
- System.out.println("another=" + another);
-
- // The most efficient lazy loader utilizing Java 8 features
- Java8Holder java8Holder = new Java8Holder();
- Heavy next = java8Holder.getHeavy();
- System.out.println("next=" + next);
- }
+public class App {
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+
+ // Simple lazy loader - not thread safe
+ HolderNaive holderNaive = new HolderNaive();
+ Heavy heavy = holderNaive.getHeavy();
+ System.out.println("heavy=" + heavy);
+
+ // Thread safe lazy loader, but with heavy synchronization on each access
+ HolderThreadSafe holderThreadSafe = new HolderThreadSafe();
+ Heavy another = holderThreadSafe.getHeavy();
+ System.out.println("another=" + another);
+
+ // The most efficient lazy loader utilizing Java 8 features
+ Java8Holder java8Holder = new Java8Holder();
+ Heavy next = java8Holder.getHeavy();
+ System.out.println("next=" + next);
+ }
}
diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java
index c2715434f..25e46d8b9 100644
--- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java
+++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java
@@ -7,13 +7,13 @@ package com.iluwatar.lazy.loading;
*/
public class Heavy {
- public Heavy() {
- System.out.println("Creating Heavy ...");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("... Heavy created");
- }
+ public Heavy() {
+ System.out.println("Creating Heavy ...");
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ System.out.println("... Heavy created");
+ }
}
diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java
index 1421d4b23..132ebaa5f 100644
--- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java
+++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java
@@ -2,22 +2,21 @@ package com.iluwatar.lazy.loading;
/**
*
- * Simple implementation of the lazy loading idiom.
- * However, this is not thread safe.
+ * Simple implementation of the lazy loading idiom. However, this is not thread safe.
*
*/
public class HolderNaive {
-
- private Heavy heavy;
-
- public HolderNaive() {
- System.out.println("HolderNaive created");
- }
- public Heavy getHeavy() {
- if (heavy == null) {
- heavy = new Heavy();
- }
- return heavy;
- }
+ private Heavy heavy;
+
+ public HolderNaive() {
+ System.out.println("HolderNaive created");
+ }
+
+ public Heavy getHeavy() {
+ if (heavy == null) {
+ heavy = new Heavy();
+ }
+ return heavy;
+ }
}
diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java
index cc039d9f0..d2b15a3af 100644
--- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java
+++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java
@@ -2,23 +2,22 @@ package com.iluwatar.lazy.loading;
/**
*
- * Same as HolderNaive but with added synchronization.
- * This implementation is thread safe, but each {@link #getHeavy()}
- * call costs additional synchronization overhead.
+ * Same as HolderNaive but with added synchronization. This implementation is thread safe, but each
+ * {@link #getHeavy()} call costs additional synchronization overhead.
*
*/
public class HolderThreadSafe {
-
- private Heavy heavy;
-
- public HolderThreadSafe() {
- System.out.println("HolderThreadSafe created");
- }
- public synchronized Heavy getHeavy() {
- if (heavy == null) {
- heavy = new Heavy();
- }
- return heavy;
- }
+ private Heavy heavy;
+
+ public HolderThreadSafe() {
+ System.out.println("HolderThreadSafe created");
+ }
+
+ public synchronized Heavy getHeavy() {
+ if (heavy == null) {
+ heavy = new Heavy();
+ }
+ return heavy;
+ }
}
diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java
index a03aae352..da021e014 100644
--- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java
+++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java
@@ -4,31 +4,34 @@ import java.util.function.Supplier;
/**
*
- * This lazy loader is thread safe and more efficient than {@link HolderThreadSafe}.
- * It utilizes Java 8 functional interface {@link Supplier} as {@link Heavy} factory.
+ * This lazy loader is thread safe and more efficient than {@link HolderThreadSafe}. It utilizes
+ * Java 8 functional interface {@link Supplier} as {@link Heavy} factory.
*
*/
public class Java8Holder {
-
- private Supplier heavy = () -> createAndCacheHeavy();
-
- public Java8Holder() {
- System.out.println("Java8Holder created");
- }
- public Heavy getHeavy() {
- return heavy.get();
- }
-
- private synchronized Heavy createAndCacheHeavy() {
- class HeavyFactory implements Supplier {
- private final Heavy heavyInstance = new Heavy();
- @Override
- public Heavy get() { return heavyInstance; }
- }
- if (!HeavyFactory.class.isInstance(heavy)) {
- heavy = new HeavyFactory();
- }
- return heavy.get();
- }
+ private Supplier heavy = () -> createAndCacheHeavy();
+
+ public Java8Holder() {
+ System.out.println("Java8Holder created");
+ }
+
+ public Heavy getHeavy() {
+ return heavy.get();
+ }
+
+ private synchronized Heavy createAndCacheHeavy() {
+ class HeavyFactory implements Supplier {
+ private final Heavy heavyInstance = new Heavy();
+
+ @Override
+ public Heavy get() {
+ return heavyInstance;
+ }
+ }
+ if (!HeavyFactory.class.isInstance(heavy)) {
+ heavy = new HeavyFactory();
+ }
+ return heavy.get();
+ }
}
diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java
index 0ef7e8ae2..591b1282d 100644
--- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java
+++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.lazy.loading.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderThreadSafeTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderThreadSafeTest.java
index f27ffc6a9..d827f186b 100644
--- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderThreadSafeTest.java
+++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderThreadSafeTest.java
@@ -8,35 +8,38 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
- * Using reflection this test shows that the heavy field is not instantiated until the method getHeavy is called
+ * Using reflection this test shows that the heavy field is not instantiated until the method
+ * getHeavy is called
*
* Created by jones on 11/10/2015.
*/
public class HolderThreadSafeTest {
- @Test
- public void test() throws IllegalAccessException {
- HolderThreadSafe hts = new HolderThreadSafe();
+ @Test
+ public void test() throws IllegalAccessException {
+ HolderThreadSafe hts = new HolderThreadSafe();
- {//first call is null
- Field[] ff = HolderThreadSafe.class.getDeclaredFields();
- for (Field f: ff) {
- f.setAccessible(true);
- }
+ {
+ // first call is null
+ Field[] ff = HolderThreadSafe.class.getDeclaredFields();
+ for (Field f : ff) {
+ f.setAccessible(true);
+ }
- assertNull(ff[0].get(hts));
- }
-
- // now it is lazily loaded
- hts.getHeavy();
-
- {//now it is not null - call via reflection so that the test is the same before and after
- Field[] ff = HolderThreadSafe.class.getDeclaredFields();
- for (Field f: ff) {
- f.setAccessible(true);
- }
-
- assertNotNull(ff[0].get(hts));
- }
+ assertNull(ff[0].get(hts));
}
+
+ // now it is lazily loaded
+ hts.getHeavy();
+
+ {
+ // now it is not null - call via reflection so that the test is the same before and after
+ Field[] ff = HolderThreadSafe.class.getDeclaredFields();
+ for (Field f : ff) {
+ f.setAccessible(true);
+ }
+
+ assertNotNull(ff[0].get(hts));
+ }
+ }
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Action.java b/mediator/src/main/java/com/iluwatar/mediator/Action.java
index a5b466342..d264f7297 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Action.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Action.java
@@ -7,25 +7,23 @@ package com.iluwatar.mediator;
*/
public enum Action {
- HUNT("hunted a rabbit", "arrives for dinner"),
- TALE("tells a tale", "comes to listen"),
- GOLD("found gold", "takes his share of the gold"),
- ENEMY("spotted enemies", "runs for cover"),
- NONE("", "");
+ HUNT("hunted a rabbit", "arrives for dinner"), TALE("tells a tale", "comes to listen"), GOLD(
+ "found gold", "takes his share of the gold"), ENEMY("spotted enemies", "runs for cover"), NONE(
+ "", "");
- private String title;
- private String description;
+ private String title;
+ private String description;
- Action(String title, String description) {
- this.title = title;
- this.description = description;
- }
+ Action(String title, String description) {
+ this.title = title;
+ this.description = description;
+ }
- public String getDescription() {
- return description;
- }
+ public String getDescription() {
+ return description;
+ }
- public String toString() {
- return title;
- }
+ public String toString() {
+ return title;
+ }
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/App.java b/mediator/src/main/java/com/iluwatar/mediator/App.java
index 9648ac608..0af9a8717 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/App.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/App.java
@@ -2,54 +2,53 @@ package com.iluwatar.mediator;
/**
*
- * The Mediator pattern defines an object that encapsulates how a set of objects
- * interact. This pattern is considered to be a behavioral pattern due to the way
- * it can alter the program's running behavior.
+ * The Mediator pattern defines an object that encapsulates how a set of objects interact. This
+ * pattern is considered to be a behavioral pattern due to the way it can alter the program's
+ * running behavior.
*
- * Usually a program is made up of a large number of classes. So the logic and
- * computation is distributed among these classes. However, as more classes are
- * developed in a program, especially during maintenance and/or refactoring,
- * the problem of communication between these classes may become more complex.
- * This makes the program harder to read and maintain. Furthermore, it can become
- * difficult to change the program, since any change may affect code in several
- * other classes.
+ * Usually a program is made up of a large number of classes. So the logic and computation is
+ * distributed among these classes. However, as more classes are developed in a program, especially
+ * during maintenance and/or refactoring, the problem of communication between these classes may
+ * become more complex. This makes the program harder to read and maintain. Furthermore, it can
+ * become difficult to change the program, since any change may affect code in several other
+ * classes.
*
- * With the Mediator pattern, communication between objects is encapsulated with
- * a mediator object. Objects no longer communicate directly with each other, but
- * instead communicate through the mediator. This reduces the dependencies between
- * communicating objects, thereby lowering the coupling.
+ * With the Mediator pattern, communication between objects is encapsulated with a mediator object.
+ * Objects no longer communicate directly with each other, but instead communicate through the
+ * mediator. This reduces the dependencies between communicating objects, thereby lowering the
+ * coupling.
*
- * In this example the mediator encapsulates how a set of objects ({@link PartyMember})
- * interact. Instead of referring to each other directly they use the mediator
- * ({@link Party}) interface.
+ * In this example the mediator encapsulates how a set of objects ({@link PartyMember}) interact.
+ * Instead of referring to each other directly they use the mediator ({@link Party}) interface.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
-
- // create party and members
- Party party = new PartyImpl();
- Hobbit hobbit = new Hobbit();
- Wizard wizard = new Wizard();
- Rogue rogue = new Rogue();
- Hunter hunter = new Hunter();
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
- // add party members
- party.addMember(hobbit);
- party.addMember(wizard);
- party.addMember(rogue);
- party.addMember(hunter);
+ // create party and members
+ Party party = new PartyImpl();
+ Hobbit hobbit = new Hobbit();
+ Wizard wizard = new Wizard();
+ Rogue rogue = new Rogue();
+ Hunter hunter = new Hunter();
- // perform actions -> the other party members
- // are notified by the party
- hobbit.act(Action.ENEMY);
- wizard.act(Action.TALE);
- rogue.act(Action.GOLD);
- hunter.act(Action.HUNT);
- }
+ // add party members
+ party.addMember(hobbit);
+ party.addMember(wizard);
+ party.addMember(rogue);
+ party.addMember(hunter);
+
+ // perform actions -> the other party members
+ // are notified by the party
+ hobbit.act(Action.ENEMY);
+ wizard.act(Action.TALE);
+ rogue.act(Action.GOLD);
+ hunter.act(Action.HUNT);
+ }
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java b/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java
index 5981a34a8..3d1bf83bf 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java
@@ -7,9 +7,9 @@ package com.iluwatar.mediator;
*/
public class Hobbit extends PartyMemberBase {
- @Override
- public String toString() {
- return "Hobbit";
- }
+ @Override
+ public String toString() {
+ return "Hobbit";
+ }
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Hunter.java b/mediator/src/main/java/com/iluwatar/mediator/Hunter.java
index 1487c836e..d6abf3416 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Hunter.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Hunter.java
@@ -7,9 +7,8 @@ package com.iluwatar.mediator;
*/
public class Hunter extends PartyMemberBase {
- @Override
- public String toString() {
- return "Hunter";
- }
-
+ @Override
+ public String toString() {
+ return "Hunter";
+ }
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Party.java b/mediator/src/main/java/com/iluwatar/mediator/Party.java
index 9328cdaa2..cb53dae27 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Party.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Party.java
@@ -7,8 +7,8 @@ package com.iluwatar.mediator;
*/
public interface Party {
- void addMember(PartyMember member);
+ void addMember(PartyMember member);
- void act(PartyMember actor, Action action);
+ void act(PartyMember actor, Action action);
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java
index 5548f5163..acc70a0e6 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java
@@ -10,24 +10,24 @@ import java.util.List;
*/
public class PartyImpl implements Party {
- private final List members;
+ private final List members;
- public PartyImpl() {
- members = new ArrayList<>();
- }
+ public PartyImpl() {
+ members = new ArrayList<>();
+ }
- @Override
- public void act(PartyMember actor, Action action) {
- for (PartyMember member : members) {
- if (member != actor) {
- member.partyAction(action);
- }
- }
- }
+ @Override
+ public void act(PartyMember actor, Action action) {
+ for (PartyMember member : members) {
+ if (member != actor) {
+ member.partyAction(action);
+ }
+ }
+ }
- @Override
- public void addMember(PartyMember member) {
- members.add(member);
- member.joinedParty(this);
- }
+ @Override
+ public void addMember(PartyMember member) {
+ members.add(member);
+ member.joinedParty(this);
+ }
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java b/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java
index fffe6dd39..0ee078070 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java
@@ -7,9 +7,9 @@ package com.iluwatar.mediator;
*/
public interface PartyMember {
- void joinedParty(Party party);
+ void joinedParty(Party party);
- void partyAction(Action action);
+ void partyAction(Action action);
- void act(Action action);
+ void act(Action action);
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java b/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java
index 7a151c355..1f58d3147 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java
@@ -7,28 +7,28 @@ package com.iluwatar.mediator;
*/
public abstract class PartyMemberBase implements PartyMember {
- protected Party party;
+ protected Party party;
- @Override
- public void joinedParty(Party party) {
- System.out.println(this + " joins the party");
- this.party = party;
- }
+ @Override
+ public void joinedParty(Party party) {
+ System.out.println(this + " joins the party");
+ this.party = party;
+ }
- @Override
- public void partyAction(Action action) {
- System.out.println(this + " " + action.getDescription());
- }
+ @Override
+ public void partyAction(Action action) {
+ System.out.println(this + " " + action.getDescription());
+ }
- @Override
- public void act(Action action) {
- if (party != null) {
- System.out.println(this + " " + action.toString());
- party.act(this, action);
- }
- }
+ @Override
+ public void act(Action action) {
+ if (party != null) {
+ System.out.println(this + " " + action.toString());
+ party.act(this, action);
+ }
+ }
- @Override
- public abstract String toString();
+ @Override
+ public abstract String toString();
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Rogue.java b/mediator/src/main/java/com/iluwatar/mediator/Rogue.java
index 69974066f..f7b005c94 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Rogue.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Rogue.java
@@ -7,9 +7,9 @@ package com.iluwatar.mediator;
*/
public class Rogue extends PartyMemberBase {
- @Override
- public String toString() {
- return "Rogue";
- }
+ @Override
+ public String toString() {
+ return "Rogue";
+ }
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Wizard.java b/mediator/src/main/java/com/iluwatar/mediator/Wizard.java
index d4d2594d7..3fdc73aa6 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Wizard.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Wizard.java
@@ -7,9 +7,9 @@ package com.iluwatar.mediator;
*/
public class Wizard extends PartyMemberBase {
- @Override
- public String toString() {
- return "Wizard";
- }
+ @Override
+ public String toString() {
+ return "Wizard";
+ }
}
diff --git a/mediator/src/test/java/com/iluwatar/mediator/AppTest.java b/mediator/src/test/java/com/iluwatar/mediator/AppTest.java
index 2b614b003..4b3269244 100644
--- a/mediator/src/test/java/com/iluwatar/mediator/AppTest.java
+++ b/mediator/src/test/java/com/iluwatar/mediator/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.mediator.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/memento/src/main/java/com/iluwatar/memento/App.java b/memento/src/main/java/com/iluwatar/memento/App.java
index 71d0ed466..c99894680 100644
--- a/memento/src/main/java/com/iluwatar/memento/App.java
+++ b/memento/src/main/java/com/iluwatar/memento/App.java
@@ -4,46 +4,45 @@ import java.util.Stack;
/**
*
- * The Memento pattern is a software design pattern that provides the ability to restore
- * an object to its previous state (undo via rollback).
+ * The Memento pattern is a software design pattern that provides the ability to restore an object
+ * to its previous state (undo via rollback).
*
- * The Memento pattern is implemented with three objects: the originator, a caretaker and
- * a memento. The originator is some object that has an internal state. The caretaker is
- * going to do something to the originator, but wants to be able to undo the change. The
- * caretaker first asks the originator for a memento object. Then it does whatever operation
- * (or sequence of operations) it was going to do. To roll back to the state before the
- * operations, it returns the memento object to the originator. The memento object itself
- * is an opaque object (one which the caretaker cannot, or should not, change). When using
- * this pattern, care should be taken if the originator may change other objects or
- * resources - the memento pattern operates on a single object.
+ * The Memento pattern is implemented with three objects: the originator, a caretaker and a memento.
+ * The originator is some object that has an internal state. The caretaker is going to do something
+ * to the originator, but wants to be able to undo the change. The caretaker first asks the
+ * originator for a memento object. Then it does whatever operation (or sequence of operations) it
+ * was going to do. To roll back to the state before the operations, it returns the memento object
+ * to the originator. The memento object itself is an opaque object (one which the caretaker cannot,
+ * or should not, change). When using this pattern, care should be taken if the originator may
+ * change other objects or resources - the memento pattern operates on a single object.
*
- * In this example the object ({@link Star})
- * gives out a "memento" ({@link StarMemento}) that contains the state of the object.
- * Later on the memento can be set back to the object restoring the state.
+ * In this example the object ({@link Star}) gives out a "memento" ({@link StarMemento}) that
+ * contains the state of the object. Later on the memento can be set back to the object restoring
+ * the state.
*
*/
public class App {
- public static void main(String[] args) {
- Stack states = new Stack<>();
+ public static void main(String[] args) {
+ Stack states = new Stack<>();
- Star star = new Star(StarType.SUN, 10000000, 500000);
- System.out.println(star);
- states.add(star.getMemento());
- star.timePasses();
- System.out.println(star);
- states.add(star.getMemento());
- star.timePasses();
- System.out.println(star);
- states.add(star.getMemento());
- star.timePasses();
- System.out.println(star);
- states.add(star.getMemento());
- star.timePasses();
- System.out.println(star);
- while (states.size() > 0) {
- star.setMemento(states.pop());
- System.out.println(star);
- }
- }
+ Star star = new Star(StarType.SUN, 10000000, 500000);
+ System.out.println(star);
+ states.add(star.getMemento());
+ star.timePasses();
+ System.out.println(star);
+ states.add(star.getMemento());
+ star.timePasses();
+ System.out.println(star);
+ states.add(star.getMemento());
+ star.timePasses();
+ System.out.println(star);
+ states.add(star.getMemento());
+ star.timePasses();
+ System.out.println(star);
+ while (states.size() > 0) {
+ star.setMemento(states.pop());
+ System.out.println(star);
+ }
+ }
}
diff --git a/memento/src/main/java/com/iluwatar/memento/Star.java b/memento/src/main/java/com/iluwatar/memento/Star.java
index 43b5c5c3c..b4ec1c669 100644
--- a/memento/src/main/java/com/iluwatar/memento/Star.java
+++ b/memento/src/main/java/com/iluwatar/memento/Star.java
@@ -7,99 +7,98 @@ package com.iluwatar.memento;
*/
public class Star {
- private StarType type;
- private int ageYears;
- private int massTons;
+ private StarType type;
+ private int ageYears;
+ private int massTons;
- public Star(StarType startType, int startAge, int startMass) {
- this.type = startType;
- this.ageYears = startAge;
- this.massTons = startMass;
- }
+ public Star(StarType startType, int startAge, int startMass) {
+ this.type = startType;
+ this.ageYears = startAge;
+ this.massTons = startMass;
+ }
- public void timePasses() {
- ageYears *= 2;
- massTons *= 8;
- switch (type) {
- case RED_GIANT:
- type = StarType.WHITE_DWARF;
- break;
- case SUN:
- type = StarType.RED_GIANT;
- break;
- case SUPERNOVA:
- type = StarType.DEAD;
- break;
- case WHITE_DWARF:
- type = StarType.SUPERNOVA;
- break;
- case DEAD:
- ageYears *= 2;
- massTons = 0;
- break;
- default:
- break;
- }
- }
+ public void timePasses() {
+ ageYears *= 2;
+ massTons *= 8;
+ switch (type) {
+ case RED_GIANT:
+ type = StarType.WHITE_DWARF;
+ break;
+ case SUN:
+ type = StarType.RED_GIANT;
+ break;
+ case SUPERNOVA:
+ type = StarType.DEAD;
+ break;
+ case WHITE_DWARF:
+ type = StarType.SUPERNOVA;
+ break;
+ case DEAD:
+ ageYears *= 2;
+ massTons = 0;
+ break;
+ default:
+ break;
+ }
+ }
- StarMemento getMemento() {
+ StarMemento getMemento() {
- StarMementoInternal state = new StarMementoInternal();
- state.setAgeYears(ageYears);
- state.setMassTons(massTons);
- state.setType(type);
- return state;
+ StarMementoInternal state = new StarMementoInternal();
+ state.setAgeYears(ageYears);
+ state.setMassTons(massTons);
+ state.setType(type);
+ return state;
- }
+ }
- void setMemento(StarMemento memento) {
+ void setMemento(StarMemento memento) {
- StarMementoInternal state = (StarMementoInternal) memento;
- this.type = state.getType();
- this.ageYears = state.getAgeYears();
- this.massTons = state.getMassTons();
+ StarMementoInternal state = (StarMementoInternal) memento;
+ this.type = state.getType();
+ this.ageYears = state.getAgeYears();
+ this.massTons = state.getMassTons();
- }
+ }
- @Override
- public String toString() {
- return String.format("%s age: %d years mass: %d tons", type.toString(),
- ageYears, massTons);
- }
-
- /**
- *
- * StarMemento implementation
- *
- */
- private static class StarMementoInternal implements StarMemento {
+ @Override
+ public String toString() {
+ return String.format("%s age: %d years mass: %d tons", type.toString(), ageYears, massTons);
+ }
- private StarType type;
- private int ageYears;
- private int massTons;
+ /**
+ *
+ * StarMemento implementation
+ *
+ */
+ private static class StarMementoInternal implements StarMemento {
- public StarType getType() {
- return type;
- }
+ private StarType type;
+ private int ageYears;
+ private int massTons;
- public void setType(StarType type) {
- this.type = type;
- }
+ public StarType getType() {
+ return type;
+ }
- public int getAgeYears() {
- return ageYears;
- }
+ public void setType(StarType type) {
+ this.type = type;
+ }
- public void setAgeYears(int ageYears) {
- this.ageYears = ageYears;
- }
+ public int getAgeYears() {
+ return ageYears;
+ }
- public int getMassTons() {
- return massTons;
- }
+ public void setAgeYears(int ageYears) {
+ this.ageYears = ageYears;
+ }
- public void setMassTons(int massTons) {
- this.massTons = massTons;
- }
- }
+ public int getMassTons() {
+ return massTons;
+ }
+
+ public void setMassTons(int massTons) {
+ this.massTons = massTons;
+ }
+ }
}
diff --git a/memento/src/main/java/com/iluwatar/memento/StarType.java b/memento/src/main/java/com/iluwatar/memento/StarType.java
index bae853097..13e84d00f 100644
--- a/memento/src/main/java/com/iluwatar/memento/StarType.java
+++ b/memento/src/main/java/com/iluwatar/memento/StarType.java
@@ -7,16 +7,17 @@ package com.iluwatar.memento;
*/
public enum StarType {
- SUN("sun"), RED_GIANT("red giant"), WHITE_DWARF("white dwarf"), SUPERNOVA("supernova"), DEAD("dead star"), UNDEFINED("");
+ SUN("sun"), RED_GIANT("red giant"), WHITE_DWARF("white dwarf"), SUPERNOVA("supernova"), DEAD(
+ "dead star"), UNDEFINED("");
- private String title;
+ private String title;
- StarType(String title) {
- this.title = title;
- }
+ StarType(String title) {
+ this.title = title;
+ }
- @Override
- public String toString() {
- return title;
- }
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/memento/src/test/java/com/iluwatar/memento/AppTest.java b/memento/src/test/java/com/iluwatar/memento/AppTest.java
index 84afd5945..4eda4a6f9 100644
--- a/memento/src/test/java/com/iluwatar/memento/AppTest.java
+++ b/memento/src/test/java/com/iluwatar/memento/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.memento.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/message-channel/src/main/java/com/iluwatar/message/channel/App.java b/message-channel/src/main/java/com/iluwatar/message/channel/App.java
index f9a334a8a..a41dd74dc 100644
--- a/message-channel/src/main/java/com/iluwatar/message/channel/App.java
+++ b/message-channel/src/main/java/com/iluwatar/message/channel/App.java
@@ -6,48 +6,48 @@ import org.apache.camel.impl.DefaultCamelContext;
/**
*
- * When two applications communicate with each other using a messaging system
- * they first need to establish a communication channel that will carry the
- * data. Message Channel decouples Message producers and consumers.
+ * When two applications communicate with each other using a messaging system they first need to
+ * establish a communication channel that will carry the data. Message Channel decouples Message
+ * producers and consumers.
*
- * The sending application doesn't necessarily know what particular application
- * will end up retrieving it, but it can be assured that the application that
- * retrieves the information is interested in that information. This is because
- * the messaging system has different Message Channels for different types of
- * information the applications want to communicate. When an application sends
- * information, it doesn't randomly add the information to any channel available;
- * it adds it to a channel whose specific purpose is to communicate that sort of
- * information. Likewise, an application that wants to receive particular information
- * doesn't pull info off some random channel; it selects what channel to get information
- * from based on what type of information it wants.
+ * The sending application doesn't necessarily know what particular application will end up
+ * retrieving it, but it can be assured that the application that retrieves the information is
+ * interested in that information. This is because the messaging system has different Message
+ * Channels for different types of information the applications want to communicate. When an
+ * application sends information, it doesn't randomly add the information to any channel available;
+ * it adds it to a channel whose specific purpose is to communicate that sort of information.
+ * Likewise, an application that wants to receive particular information doesn't pull info off some
+ * random channel; it selects what channel to get information from based on what type of information
+ * it wants.
*
- * In this example we use Apache Camel to establish two different Message Channels. The first
- * one reads from standard input and delivers messages to Direct endpoint. The second Message
- * Channel is established from the Direct component to console output. No actual messages are sent,
- * only the established routes are printed to standard output.
+ * In this example we use Apache Camel to establish two different Message Channels. The first one
+ * reads from standard input and delivers messages to Direct endpoint. The second Message Channel is
+ * established from the Direct component to console output. No actual messages are sent, only the
+ * established routes are printed to standard output.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- CamelContext context = new DefaultCamelContext();
-
- context.addRoutes(new RouteBuilder() {
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ * @throws Exception
+ */
+ public static void main(String[] args) throws Exception {
+ CamelContext context = new DefaultCamelContext();
- @Override
- public void configure() throws Exception {
- from("stream:in").to("direct:greetings");
- from("direct:greetings").to("stream:out");
- }
- });
-
- context.start();
- context.getRoutes().stream().forEach((r) -> System.out.println(r));
- context.stop();
- }
+ context.addRoutes(new RouteBuilder() {
+
+ @Override
+ public void configure() throws Exception {
+ from("stream:in").to("direct:greetings");
+ from("direct:greetings").to("stream:out");
+ }
+ });
+
+ context.start();
+ context.getRoutes().stream().forEach((r) -> System.out.println(r));
+ context.stop();
+ }
}
diff --git a/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java b/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java
index fa3af1161..d36fff43f 100644
--- a/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java
+++ b/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java
@@ -8,10 +8,10 @@ import org.junit.Test;
*
*/
public class AppTest {
-
- @Test
- public void test() throws Exception {
- String[] args = {};
- App.main(args);
- }
+
+ @Test
+ public void test() throws Exception {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java
index 0ba34b5d4..097ea3932 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java
@@ -5,34 +5,37 @@ package com.iluwatar.model.view.controller;
* Model-View-Controller is a pattern for implementing user interfaces. It divides the application
* into three interconnected parts namely the model, the view and the controller.
*
- * The central component of MVC, the model, captures the behavior of the application in terms of its problem
- * domain, independent of the user interface. The model directly manages the data, logic and rules of the
- * application. A view can be any output representation of information, such as a chart or a diagram
- * The third part, the controller, accepts input and converts it to commands for the model or view.
+ * The central component of MVC, the model, captures the behavior of the application in terms of its
+ * problem domain, independent of the user interface. The model directly manages the data, logic and
+ * rules of the application. A view can be any output representation of information, such as a chart
+ * or a diagram The third part, the controller, accepts input and converts it to commands for the
+ * model or view.
*
- * In this example we have a giant ({@link GiantModel}) with statuses for health, fatigue and nourishment. {@link GiantView}
- * can display the giant with its current status. {@link GiantController} receives input affecting the model and
- * delegates redrawing the giant to the view.
+ * In this example we have a giant ({@link GiantModel}) with statuses for health, fatigue and
+ * nourishment. {@link GiantView} can display the giant with its current status.
+ * {@link GiantController} receives input affecting the model and delegates redrawing the giant to
+ * the view.
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
- // create model, view and controller
- GiantModel giant = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
- GiantView view = new GiantView();
- GiantController controller = new GiantController(giant, view);
- // initial display
- controller.updateView();
- // controller receives some interactions that affect the giant
- controller.setHealth(Health.WOUNDED);
- controller.setNourishment(Nourishment.HUNGRY);
- controller.setFatigue(Fatigue.TIRED);
- // redisplay
- controller.updateView();
- }
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ // create model, view and controller
+ GiantModel giant = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
+ GiantView view = new GiantView();
+ GiantController controller = new GiantController(giant, view);
+ // initial display
+ controller.updateView();
+ // controller receives some interactions that affect the giant
+ controller.setHealth(Health.WOUNDED);
+ controller.setNourishment(Nourishment.HUNGRY);
+ controller.setFatigue(Fatigue.TIRED);
+ // redisplay
+ controller.updateView();
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java
index d19df6a8c..d4a60ba93 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java
@@ -7,16 +7,16 @@ package com.iluwatar.model.view.controller;
*/
public enum Fatigue {
- ALERT("alert"), TIRED("tired"), SLEEPING("sleeping");
-
- private String title;
-
- Fatigue(String title) {
- this.title = title;
- }
+ ALERT("alert"), TIRED("tired"), SLEEPING("sleeping");
- @Override
- public String toString() {
- return title;
- }
+ private String title;
+
+ Fatigue(String title) {
+ this.title = title;
+ }
+
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java
index acda727d9..42dcaf539 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java
@@ -7,39 +7,39 @@ package com.iluwatar.model.view.controller;
*/
public class GiantController {
- private GiantModel giant;
- private GiantView view;
+ private GiantModel giant;
+ private GiantView view;
- public GiantController(GiantModel giant, GiantView view) {
- this.giant = giant;
- this.view = view;
- }
-
- public Health getHealth() {
- return giant.getHealth();
- }
+ public GiantController(GiantModel giant, GiantView view) {
+ this.giant = giant;
+ this.view = view;
+ }
- public void setHealth(Health health) {
- this.giant.setHealth(health);
- }
+ public Health getHealth() {
+ return giant.getHealth();
+ }
- public Fatigue getFatigue() {
- return giant.getFatigue();
- }
+ public void setHealth(Health health) {
+ this.giant.setHealth(health);
+ }
- public void setFatigue(Fatigue fatigue) {
- this.giant.setFatigue(fatigue);
- }
+ public Fatigue getFatigue() {
+ return giant.getFatigue();
+ }
- public Nourishment getNourishment() {
- return giant.getNourishment();
- }
+ public void setFatigue(Fatigue fatigue) {
+ this.giant.setFatigue(fatigue);
+ }
- public void setNourishment(Nourishment nourishment) {
- this.giant.setNourishment(nourishment);
- }
-
- public void updateView() {
- this.view.displayGiant(giant);
- }
+ public Nourishment getNourishment() {
+ return giant.getNourishment();
+ }
+
+ public void setNourishment(Nourishment nourishment) {
+ this.giant.setNourishment(nourishment);
+ }
+
+ public void updateView() {
+ this.view.displayGiant(giant);
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java
index 97c298768..2ecbe8b1f 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java
@@ -6,43 +6,43 @@ package com.iluwatar.model.view.controller;
*
*/
public class GiantModel {
-
- private Health health;
- private Fatigue fatigue;
- private Nourishment nourishment;
- GiantModel(Health health, Fatigue fatigue, Nourishment nourishment) {
- this.health = health;
- this.fatigue = fatigue;
- this.nourishment = nourishment;
- }
+ private Health health;
+ private Fatigue fatigue;
+ private Nourishment nourishment;
- public Health getHealth() {
- return health;
- }
+ GiantModel(Health health, Fatigue fatigue, Nourishment nourishment) {
+ this.health = health;
+ this.fatigue = fatigue;
+ this.nourishment = nourishment;
+ }
- public void setHealth(Health health) {
- this.health = health;
- }
+ public Health getHealth() {
+ return health;
+ }
- public Fatigue getFatigue() {
- return fatigue;
- }
+ public void setHealth(Health health) {
+ this.health = health;
+ }
- public void setFatigue(Fatigue fatigue) {
- this.fatigue = fatigue;
- }
+ public Fatigue getFatigue() {
+ return fatigue;
+ }
- public Nourishment getNourishment() {
- return nourishment;
- }
+ public void setFatigue(Fatigue fatigue) {
+ this.fatigue = fatigue;
+ }
- public void setNourishment(Nourishment nourishment) {
- this.nourishment = nourishment;
- }
-
- @Override
- public String toString() {
- return String.format("The giant looks %s, %s and %s.", health, fatigue, nourishment);
- }
+ public Nourishment getNourishment() {
+ return nourishment;
+ }
+
+ public void setNourishment(Nourishment nourishment) {
+ this.nourishment = nourishment;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("The giant looks %s, %s and %s.", health, fatigue, nourishment);
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java
index 1cf5e20a6..5b2c8e840 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java
@@ -7,7 +7,7 @@ package com.iluwatar.model.view.controller;
*/
public class GiantView {
- public void displayGiant(GiantModel giant) {
- System.out.println(giant);
- }
+ public void displayGiant(GiantModel giant) {
+ System.out.println(giant);
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java
index feaec81d7..9bde455dd 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java
@@ -6,17 +6,17 @@ package com.iluwatar.model.view.controller;
*
*/
public enum Health {
-
- HEALTHY("healthy"), WOUNDED("wounded"), DEAD("dead");
-
- private String title;
-
- Health(String title) {
- this.title = title;
- }
- @Override
- public String toString() {
- return title;
- }
+ HEALTHY("healthy"), WOUNDED("wounded"), DEAD("dead");
+
+ private String title;
+
+ Health(String title) {
+ this.title = title;
+ }
+
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java
index 7bab931b6..c3e043906 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java
@@ -7,16 +7,16 @@ package com.iluwatar.model.view.controller;
*/
public enum Nourishment {
- SATURATED("saturated"), HUNGRY("hungry"), STARVING("starving");
-
- private String title;
-
- Nourishment(String title) {
- this.title = title;
- }
+ SATURATED("saturated"), HUNGRY("hungry"), STARVING("starving");
- @Override
- public String toString() {
- return title;
- }
+ private String title;
+
+ Nourishment(String title) {
+ this.title = title;
+ }
+
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java
index 4bb31f6e6..7142c2979 100644
--- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java
+++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java
@@ -10,10 +10,10 @@ import com.iluwatar.model.view.controller.App;
*
*/
public class AppTest {
-
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java
index ac6ccf091..2dc3f4d51 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java
@@ -2,30 +2,31 @@ package com.iluwatar.model.view.presenter;
/**
*
- * The Model-View-Presenter(MVP) architectural pattern, helps us achieve what is
- * called "The separation of concerns" principle. This is accomplished
- * by separating the application's logic (Model), GUIs (View), and finally
- * the way that the user's actions update the application's logic (Presenter).
+ * The Model-View-Presenter(MVP) architectural pattern, helps us achieve what is called
+ * "The separation of concerns" principle. This is accomplished by separating the application's
+ * logic (Model), GUIs (View), and finally the way that the user's actions update the application's
+ * logic (Presenter).
*
- * In the following example, The {@link FileLoader} class represents the app's logic,
- * the {@link FileSelectorJFrame} is the GUI and the {@link FileSelectorPresenter} is
- * responsible to respond to users' actions.
+ * In the following example, The {@link FileLoader} class represents the app's logic, the
+ * {@link FileSelectorJFrame} is the GUI and the {@link FileSelectorPresenter} is responsible to
+ * respond to users' actions.
*
- * Finally, please notice the wiring between the Presenter and the View
- * and between the Presenter and the Model.
+ * Finally, please notice the wiring between the Presenter and the View and between the Presenter
+ * and the Model.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- FileLoader loader = new FileLoader();
- FileSelectorJFrame jFrame = new FileSelectorJFrame();
- FileSelectorPresenter presenter = new FileSelectorPresenter(jFrame);
- presenter.setLoader(loader);
- presenter.start();
- }
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ FileLoader loader = new FileLoader();
+ FileSelectorJFrame jFrame = new FileSelectorJFrame();
+ FileSelectorPresenter presenter = new FileSelectorPresenter(jFrame);
+ presenter.setLoader(loader);
+ presenter.start();
+ }
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java
index 96d843f83..d04f284ac 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java
@@ -5,76 +5,76 @@ import java.io.File;
import java.io.FileReader;
/**
- * Every instance of this class represents the Model component in the
- * Model-View-Presenter architectural pattern.
+ * Every instance of this class represents the Model component in the Model-View-Presenter
+ * architectural pattern.
*
* It is responsible for reading and loading the contents of a given file.
*/
public class FileLoader {
- /**
- * Indicates if the file is loaded or not.
- */
- private boolean loaded = false;
+ /**
+ * Indicates if the file is loaded or not.
+ */
+ private boolean loaded = false;
- /**
- * The name of the file that we want to load.
- */
- private String fileName;
+ /**
+ * The name of the file that we want to load.
+ */
+ private String fileName;
- /**
- * Loads the data of the file specified.
- */
- public String loadData() {
- try {
- BufferedReader br = new BufferedReader(new FileReader(new File(
- this.fileName)));
- StringBuilder sb = new StringBuilder();
- String line;
+ /**
+ * Loads the data of the file specified.
+ */
+ public String loadData() {
+ try {
+ BufferedReader br = new BufferedReader(new FileReader(new File(this.fileName)));
+ StringBuilder sb = new StringBuilder();
+ String line;
- while ((line = br.readLine()) != null) {
- sb.append(line).append('\n');
- }
+ while ((line = br.readLine()) != null) {
+ sb.append(line).append('\n');
+ }
- this.loaded = true;
- br.close();
+ this.loaded = true;
+ br.close();
- return sb.toString();
- }
+ return sb.toString();
+ }
- catch (Exception e) {
- e.printStackTrace();
- }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
- return null;
- }
+ return null;
+ }
- /**
- * Sets the path of the file to be loaded, to the given value.
- * @param fileName The path of the file to be loaded.
- */
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
+ /**
+ * Sets the path of the file to be loaded, to the given value.
+ *
+ * @param fileName The path of the file to be loaded.
+ */
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
- /**
- * @return fileName The path of the file to be loaded.
- */
- public String getFileName() {
- return this.fileName;
- }
+ /**
+ * @return fileName The path of the file to be loaded.
+ */
+ public String getFileName() {
+ return this.fileName;
+ }
- /**
- * @return True, if the file given exists, false otherwise.
- */
- public boolean fileExists() {
- return new File(this.fileName).exists();
- }
+ /**
+ * @return True, if the file given exists, false otherwise.
+ */
+ public boolean fileExists() {
+ return new File(this.fileName).exists();
+ }
- /**
- * @return True, if the file is loaded, false otherwise.
- */
- public boolean isLoaded() {
- return this.loaded;
- }
+ /**
+ * @return True, if the file is loaded, false otherwise.
+ */
+ public boolean isLoaded() {
+ return this.loaded;
+ }
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java
index f4d24f59f..02cb2703a 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java
@@ -14,187 +14,185 @@ import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
- * This class is the GUI implementation of the View component in the
- * Model-View-Presenter pattern.
+ * This class is the GUI implementation of the View component in the Model-View-Presenter pattern.
*/
-public class FileSelectorJFrame extends JFrame implements FileSelectorView,
- ActionListener {
+public class FileSelectorJFrame extends JFrame implements FileSelectorView, ActionListener {
- /**
- * Default serial version ID.
- */
- private static final long serialVersionUID = 1L;
+ /**
+ * Default serial version ID.
+ */
+ private static final long serialVersionUID = 1L;
- /**
- * The "OK" button for loading the file.
- */
- private JButton OK;
+ /**
+ * The "OK" button for loading the file.
+ */
+ private JButton OK;
- /**
- * The cancel button.
- */
- private JButton cancel;
+ /**
+ * The cancel button.
+ */
+ private JButton cancel;
- /**
- * The information label.
- */
- private JLabel info;
+ /**
+ * The information label.
+ */
+ private JLabel info;
- /**
- * The contents label.
- */
- private JLabel contents;
+ /**
+ * The contents label.
+ */
+ private JLabel contents;
- /**
- * The text field for giving the name of the file that we want to open.
- */
- private JTextField input;
+ /**
+ * The text field for giving the name of the file that we want to open.
+ */
+ private JTextField input;
- /**
- * A text area that will keep the contents of the file opened.
- */
- private JTextArea area;
+ /**
+ * A text area that will keep the contents of the file opened.
+ */
+ private JTextArea area;
- /**
- * The panel that will hold our widgets.
- */
- private JPanel panel;
+ /**
+ * The panel that will hold our widgets.
+ */
+ private JPanel panel;
- /**
- * The Presenter component that the frame will interact with
- */
- private FileSelectorPresenter presenter;
+ /**
+ * The Presenter component that the frame will interact with
+ */
+ private FileSelectorPresenter presenter;
- /**
- * The name of the file that we want to read it's contents.
- */
- private String fileName;
+ /**
+ * The name of the file that we want to read it's contents.
+ */
+ private String fileName;
- /**
- * Constructor.
- */
- public FileSelectorJFrame() {
- super("File Loader");
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- this.setLayout(null);
- this.setBounds(100, 100, 500, 200);
+ /**
+ * Constructor.
+ */
+ public FileSelectorJFrame() {
+ super("File Loader");
+ this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ this.setLayout(null);
+ this.setBounds(100, 100, 500, 200);
- /*
- * Add the panel.
- */
- this.panel = new JPanel();
- panel.setLayout(null);
- this.add(panel);
- panel.setBounds(0, 0, 500, 200);
- panel.setBackground(Color.LIGHT_GRAY);
+ /*
+ * Add the panel.
+ */
+ this.panel = new JPanel();
+ panel.setLayout(null);
+ this.add(panel);
+ panel.setBounds(0, 0, 500, 200);
+ panel.setBackground(Color.LIGHT_GRAY);
- /*
- * Add the info label.
- */
- this.info = new JLabel("File Name :");
- this.panel.add(info);
- info.setBounds(30, 10, 100, 30);
+ /*
+ * Add the info label.
+ */
+ this.info = new JLabel("File Name :");
+ this.panel.add(info);
+ info.setBounds(30, 10, 100, 30);
- /*
- * Add the contents label.
- */
- this.contents = new JLabel("File contents :");
- this.panel.add(contents);
- this.contents.setBounds(30, 100, 120, 30);
+ /*
+ * Add the contents label.
+ */
+ this.contents = new JLabel("File contents :");
+ this.panel.add(contents);
+ this.contents.setBounds(30, 100, 120, 30);
- /*
- * Add the text field.
- */
- this.input = new JTextField(100);
- this.panel.add(input);
- this.input.setBounds(150, 15, 200, 20);
+ /*
+ * Add the text field.
+ */
+ this.input = new JTextField(100);
+ this.panel.add(input);
+ this.input.setBounds(150, 15, 200, 20);
- /*
- * Add the text area.
- */
- this.area = new JTextArea(100, 100);
- JScrollPane pane = new JScrollPane(area);
- pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
- pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
- this.panel.add(pane);
- this.area.setEditable(false);
- pane.setBounds(150, 100, 250, 80);
+ /*
+ * Add the text area.
+ */
+ this.area = new JTextArea(100, 100);
+ JScrollPane pane = new JScrollPane(area);
+ pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
+ pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
+ this.panel.add(pane);
+ this.area.setEditable(false);
+ pane.setBounds(150, 100, 250, 80);
- /*
- * Add the OK button.
- */
- this.OK = new JButton("OK");
- this.panel.add(OK);
- this.OK.setBounds(250, 50, 100, 25);
- this.OK.addActionListener(this);
+ /*
+ * Add the OK button.
+ */
+ this.OK = new JButton("OK");
+ this.panel.add(OK);
+ this.OK.setBounds(250, 50, 100, 25);
+ this.OK.addActionListener(this);
- /*
- * Add the cancel button.
- */
- this.cancel = new JButton("Cancel");
- this.panel.add(this.cancel);
- this.cancel.setBounds(380, 50, 100, 25);
- this.cancel.addActionListener(this);
+ /*
+ * Add the cancel button.
+ */
+ this.cancel = new JButton("Cancel");
+ this.panel.add(this.cancel);
+ this.cancel.setBounds(380, 50, 100, 25);
+ this.cancel.addActionListener(this);
- this.presenter = null;
- this.fileName = null;
- }
+ this.presenter = null;
+ this.fileName = null;
+ }
- @Override
- public void actionPerformed(ActionEvent e) {
- if (e.getSource() == this.OK) {
- this.fileName = this.input.getText();
- presenter.fileNameChanged();
- presenter.confirmed();
- }
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ if (e.getSource() == this.OK) {
+ this.fileName = this.input.getText();
+ presenter.fileNameChanged();
+ presenter.confirmed();
+ }
- else if (e.getSource() == this.cancel) {
- presenter.cancelled();
- }
- }
+ else if (e.getSource() == this.cancel) {
+ presenter.cancelled();
+ }
+ }
- @Override
- public void open() {
- this.setVisible(true);
- }
+ @Override
+ public void open() {
+ this.setVisible(true);
+ }
- @Override
- public void close() {
- this.dispose();
- }
+ @Override
+ public void close() {
+ this.dispose();
+ }
- @Override
- public boolean isOpened() {
- return this.isVisible();
- }
+ @Override
+ public boolean isOpened() {
+ return this.isVisible();
+ }
- @Override
- public void setPresenter(FileSelectorPresenter presenter) {
- this.presenter = presenter;
- }
+ @Override
+ public void setPresenter(FileSelectorPresenter presenter) {
+ this.presenter = presenter;
+ }
- @Override
- public FileSelectorPresenter getPresenter() {
- return this.presenter;
- }
+ @Override
+ public FileSelectorPresenter getPresenter() {
+ return this.presenter;
+ }
- @Override
- public void setFileName(String name) {
- this.fileName = name;
- }
+ @Override
+ public void setFileName(String name) {
+ this.fileName = name;
+ }
- @Override
- public String getFileName() {
- return this.fileName;
- }
+ @Override
+ public String getFileName() {
+ return this.fileName;
+ }
- @Override
- public void showMessage(String message) {
- JOptionPane.showMessageDialog(null, message);
- }
+ @Override
+ public void showMessage(String message) {
+ JOptionPane.showMessageDialog(null, message);
+ }
- @Override
- public void displayData(String data) {
- this.area.setText(data);
- }
+ @Override
+ public void displayData(String data) {
+ this.area.setText(data);
+ }
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java
index 7119d60bf..133d8555d 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java
@@ -1,75 +1,76 @@
package com.iluwatar.model.view.presenter;
/**
- * Every instance of this class represents the Presenter component in the
- * Model-View-Presenter architectural pattern.
+ * Every instance of this class represents the Presenter component in the Model-View-Presenter
+ * architectural pattern.
*
- * It is responsible for reacting to the user's actions and update the View
- * component.
+ * It is responsible for reacting to the user's actions and update the View component.
*/
public class FileSelectorPresenter {
- /**
- * The View component that the presenter interacts with.
- */
- private FileSelectorView view;
+ /**
+ * The View component that the presenter interacts with.
+ */
+ private FileSelectorView view;
- /**
- * The Model component that the presenter interacts with.
- */
- private FileLoader loader;
+ /**
+ * The Model component that the presenter interacts with.
+ */
+ private FileLoader loader;
- /**
- * Constructor
- * @param view The view component that the presenter will interact with.
- */
- public FileSelectorPresenter(FileSelectorView view) {
- this.view = view;
- }
+ /**
+ * Constructor
+ *
+ * @param view The view component that the presenter will interact with.
+ */
+ public FileSelectorPresenter(FileSelectorView view) {
+ this.view = view;
+ }
- /**
- * Sets the {@link FileLoader} object, to the value given as parameter.
- * @param loader The new {@link FileLoader} object(the Model component).
- */
- public void setLoader(FileLoader loader) {
- this.loader = loader;
- }
+ /**
+ * Sets the {@link FileLoader} object, to the value given as parameter.
+ *
+ * @param loader The new {@link FileLoader} object(the Model component).
+ */
+ public void setLoader(FileLoader loader) {
+ this.loader = loader;
+ }
- /**
- * Starts the presenter.
- */
- public void start() {
- view.setPresenter(this);
- view.open();
- }
+ /**
+ * Starts the presenter.
+ */
+ public void start() {
+ view.setPresenter(this);
+ view.open();
+ }
- /**
- * An "event" that fires when the name of the file to be loaded changes.
- */
- public void fileNameChanged() {
- loader.setFileName(view.getFileName());
- }
+ /**
+ * An "event" that fires when the name of the file to be loaded changes.
+ */
+ public void fileNameChanged() {
+ loader.setFileName(view.getFileName());
+ }
- public void confirmed() {
- if (loader.getFileName() == null || loader.getFileName().equals("")) {
- view.showMessage("Please give the name of the file first!");
- return;
- }
+ public void confirmed() {
+ if (loader.getFileName() == null || loader.getFileName().equals("")) {
+ view.showMessage("Please give the name of the file first!");
+ return;
+ }
- if (loader.fileExists()) {
- String data = loader.loadData();
- view.displayData(data);
- }
+ if (loader.fileExists()) {
+ String data = loader.loadData();
+ view.displayData(data);
+ }
- else {
- view.showMessage("The file specified does not exist.");
- }
- }
+ else {
+ view.showMessage("The file specified does not exist.");
+ }
+ }
- /**
- * Cancels the file loading process.
- */
- public void cancelled() {
- view.close();
- }
+ /**
+ * Cancels the file loading process.
+ */
+ public void cancelled() {
+ view.close();
+ }
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java
index d0cec4c40..ac338ef22 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java
@@ -1,109 +1,109 @@
package com.iluwatar.model.view.presenter;
/**
- * Every instance of this class represents the Stub component in the
- * Model-View-Presenter architectural pattern.
+ * Every instance of this class represents the Stub component in the Model-View-Presenter
+ * architectural pattern.
*
- * The stub implements the View interface and it is useful when we want the test
- * the reaction to user events, such as mouse clicks.
+ * The stub implements the View interface and it is useful when we want the test the reaction to
+ * user events, such as mouse clicks.
*
- * Since we can not test the GUI directly, the MVP pattern provides this
- * functionality through the View's dummy implementation, the Stub.
+ * Since we can not test the GUI directly, the MVP pattern provides this functionality through the
+ * View's dummy implementation, the Stub.
*/
public class FileSelectorStub implements FileSelectorView {
- /**
- * Indicates whether or not the view is opened.
- */
- private boolean opened;
+ /**
+ * Indicates whether or not the view is opened.
+ */
+ private boolean opened;
- /**
- * The presenter Component.
- */
- private FileSelectorPresenter presenter;
+ /**
+ * The presenter Component.
+ */
+ private FileSelectorPresenter presenter;
- /**
- * The current name of the file.
- */
- private String name;
+ /**
+ * The current name of the file.
+ */
+ private String name;
- /**
- * Indicates the number of messages that were "displayed" to the user.
- */
- private int numOfMessageSent;
+ /**
+ * Indicates the number of messages that were "displayed" to the user.
+ */
+ private int numOfMessageSent;
- /**
- * Indicates if the data of the file where displayed or not.
- */
- private boolean dataDisplayed;
+ /**
+ * Indicates if the data of the file where displayed or not.
+ */
+ private boolean dataDisplayed;
- /**
- * Constructor
- */
- public FileSelectorStub() {
- this.opened = false;
- this.presenter = null;
- this.name = "";
- this.numOfMessageSent = 0;
- this.dataDisplayed = false;
- }
+ /**
+ * Constructor
+ */
+ public FileSelectorStub() {
+ this.opened = false;
+ this.presenter = null;
+ this.name = "";
+ this.numOfMessageSent = 0;
+ this.dataDisplayed = false;
+ }
- @Override
- public void open() {
- this.opened = true;
- }
+ @Override
+ public void open() {
+ this.opened = true;
+ }
- @Override
- public void setPresenter(FileSelectorPresenter presenter) {
- this.presenter = presenter;
- }
+ @Override
+ public void setPresenter(FileSelectorPresenter presenter) {
+ this.presenter = presenter;
+ }
- @Override
- public boolean isOpened() {
- return this.opened;
- }
+ @Override
+ public boolean isOpened() {
+ return this.opened;
+ }
- @Override
- public FileSelectorPresenter getPresenter() {
- return this.presenter;
- }
+ @Override
+ public FileSelectorPresenter getPresenter() {
+ return this.presenter;
+ }
- @Override
- public String getFileName() {
- return this.name;
- }
+ @Override
+ public String getFileName() {
+ return this.name;
+ }
- @Override
- public void setFileName(String name) {
- this.name = name;
- }
+ @Override
+ public void setFileName(String name) {
+ this.name = name;
+ }
- @Override
- public void showMessage(String message) {
- this.numOfMessageSent++;
- }
+ @Override
+ public void showMessage(String message) {
+ this.numOfMessageSent++;
+ }
- @Override
- public void close() {
- this.opened = false;
- }
+ @Override
+ public void close() {
+ this.opened = false;
+ }
- @Override
- public void displayData(String data) {
- this.dataDisplayed = true;
- }
+ @Override
+ public void displayData(String data) {
+ this.dataDisplayed = true;
+ }
- /**
- * Returns the number of messages that were displayed to the user.
- */
- public int getMessagesSent() {
- return this.numOfMessageSent;
- }
+ /**
+ * Returns the number of messages that were displayed to the user.
+ */
+ public int getMessagesSent() {
+ return this.numOfMessageSent;
+ }
- /**
- * @return True if the data where displayed, false otherwise.
- */
- public boolean dataDisplayed() {
- return this.dataDisplayed;
- }
+ /**
+ * @return True if the data where displayed, false otherwise.
+ */
+ public boolean dataDisplayed() {
+ return this.dataDisplayed;
+ }
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java
index 8cd265f9b..80cfadd28 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java
@@ -1,57 +1,61 @@
package com.iluwatar.model.view.presenter;
/**
- * This interface represents the View component in the Model-View-Presenter
- * pattern. It can be implemented by either the GUI components, or by the Stub.
+ * This interface represents the View component in the Model-View-Presenter pattern. It can be
+ * implemented by either the GUI components, or by the Stub.
*/
public interface FileSelectorView {
- /**
- * Opens the view.
- */
- public void open();
+ /**
+ * Opens the view.
+ */
+ public void open();
- /**
- * Closes the view.
- */
- public void close();
+ /**
+ * Closes the view.
+ */
+ public void close();
- /**
- * @return True, if the view is opened, false otherwise.
- */
- public boolean isOpened();
+ /**
+ * @return True, if the view is opened, false otherwise.
+ */
+ public boolean isOpened();
- /**
- * Sets the presenter component, to the one given as parameter.
- * @param presenter The new presenter component.
- */
- public void setPresenter(FileSelectorPresenter presenter);
+ /**
+ * Sets the presenter component, to the one given as parameter.
+ *
+ * @param presenter The new presenter component.
+ */
+ public void setPresenter(FileSelectorPresenter presenter);
- /**
- * @return The presenter Component.
- */
- public FileSelectorPresenter getPresenter();
+ /**
+ * @return The presenter Component.
+ */
+ public FileSelectorPresenter getPresenter();
- /**
- * Sets the file's name, to the value given as parameter.
- * @param name The new name of the file.
- */
- public void setFileName(String name);
+ /**
+ * Sets the file's name, to the value given as parameter.
+ *
+ * @param name The new name of the file.
+ */
+ public void setFileName(String name);
- /**
- * @return The name of the file.
- */
- public String getFileName();
+ /**
+ * @return The name of the file.
+ */
+ public String getFileName();
- /**
- * Displays a message to the users.
- * @param message The message to be displayed.
- */
- public void showMessage(String message);
+ /**
+ * Displays a message to the users.
+ *
+ * @param message The message to be displayed.
+ */
+ public void showMessage(String message);
- /**
- * Displays the data to the view.
- * @param data The data to be written.
- */
- public void displayData(String data);
+ /**
+ * Displays the data to the view.
+ *
+ * @param data The data to be written.
+ */
+ public void displayData(String data);
}
diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java
index 119448e9c..dfdcba31b 100644
--- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java
+++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java
@@ -10,116 +10,115 @@ import com.iluwatar.model.view.presenter.FileSelectorPresenter;
import com.iluwatar.model.view.presenter.FileSelectorStub;
/**
- * This test case is responsible for testing our application by taking advantage
- * of the Model-View-Controller architectural pattern.
+ * This test case is responsible for testing our application by taking advantage of the
+ * Model-View-Controller architectural pattern.
*/
public class FileSelectorPresenterTest {
- /**
- * The Presenter component.
- */
- private FileSelectorPresenter presenter;
+ /**
+ * The Presenter component.
+ */
+ private FileSelectorPresenter presenter;
- /**
- * The View component, implemented this time as a Stub!!!
- */
- private FileSelectorStub stub;
+ /**
+ * The View component, implemented this time as a Stub!!!
+ */
+ private FileSelectorStub stub;
- /**
- * The Model component.
- */
- private FileLoader loader;
+ /**
+ * The Model component.
+ */
+ private FileLoader loader;
- /**
- * Initializes the components of the test case.
- */
- @Before
- public void setUp() {
- this.stub = new FileSelectorStub();
- this.loader = new FileLoader();
- presenter = new FileSelectorPresenter(this.stub);
- presenter.setLoader(loader);
- }
+ /**
+ * Initializes the components of the test case.
+ */
+ @Before
+ public void setUp() {
+ this.stub = new FileSelectorStub();
+ this.loader = new FileLoader();
+ presenter = new FileSelectorPresenter(this.stub);
+ presenter.setLoader(loader);
+ }
- /**
- * Tests if the Presenter was successfully connected with the View.
- */
- @Test
- public void wiring() {
- presenter.start();
+ /**
+ * Tests if the Presenter was successfully connected with the View.
+ */
+ @Test
+ public void wiring() {
+ presenter.start();
- assertNotNull(stub.getPresenter());
- assertTrue(stub.isOpened());
- }
+ assertNotNull(stub.getPresenter());
+ assertTrue(stub.isOpened());
+ }
- /**
- * Tests if the name of the file changes.
- */
- @Test
- public void updateFileNameToLoader() {
- String EXPECTED_FILE = "Stamatis";
- stub.setFileName(EXPECTED_FILE);
+ /**
+ * Tests if the name of the file changes.
+ */
+ @Test
+ public void updateFileNameToLoader() {
+ String EXPECTED_FILE = "Stamatis";
+ stub.setFileName(EXPECTED_FILE);
- presenter.start();
- presenter.fileNameChanged();
+ presenter.start();
+ presenter.fileNameChanged();
- assertEquals(EXPECTED_FILE, loader.getFileName());
- }
+ assertEquals(EXPECTED_FILE, loader.getFileName());
+ }
- /**
- * Tests if we receive a confirmation when we attempt to open a file that
- * it's name is null or an empty string.
- */
- @Test
- public void fileConfirmationWhenNameIsNull() {
- stub.setFileName(null);
+ /**
+ * Tests if we receive a confirmation when we attempt to open a file that it's name is null or an
+ * empty string.
+ */
+ @Test
+ public void fileConfirmationWhenNameIsNull() {
+ stub.setFileName(null);
- presenter.start();
- presenter.fileNameChanged();
- presenter.confirmed();
+ presenter.start();
+ presenter.fileNameChanged();
+ presenter.confirmed();
- assertFalse(loader.isLoaded());
- assertEquals(1, stub.getMessagesSent());
- }
+ assertFalse(loader.isLoaded());
+ assertEquals(1, stub.getMessagesSent());
+ }
- /**
- * Tests if we receive a confirmation when we attempt to open a file that it
- * doesn't exist.
- */
- @Test
- public void fileConfirmationWhenFileDoesNotExist() {
- stub.setFileName("RandomName.txt");
+ /**
+ * Tests if we receive a confirmation when we attempt to open a file that it doesn't exist.
+ */
+ @Test
+ public void fileConfirmationWhenFileDoesNotExist() {
+ stub.setFileName("RandomName.txt");
- presenter.start();
- presenter.fileNameChanged();
- presenter.confirmed();
+ presenter.start();
+ presenter.fileNameChanged();
+ presenter.confirmed();
- assertFalse(loader.isLoaded());
- assertEquals(1, stub.getMessagesSent());
- }
+ assertFalse(loader.isLoaded());
+ assertEquals(1, stub.getMessagesSent());
+ }
- /**
- * Tests if we can open the file, when it exists.
- */
- @Test
- public void fileConfirmationWhenFileExists() {
- stub.setFileName("etc/data/test.txt");
- presenter.start();
- presenter.fileNameChanged();
- presenter.confirmed();
+ /**
+ * Tests if we can open the file, when it exists.
+ */
+ @Test
+ public void fileConfirmationWhenFileExists() {
+ stub.setFileName("etc/data/test.txt");
+ presenter.start();
+ presenter.fileNameChanged();
+ presenter.confirmed();
- assertTrue(loader.isLoaded());
- assertTrue(stub.dataDisplayed());
- }
+ assertTrue(loader.isLoaded());
+ assertTrue(stub.dataDisplayed());
+ }
- /**
- * Tests if the view closes after cancellation.
- */
- @Test
- public void cancellation() {
- presenter.start();
- presenter.cancelled();
+ /**
+ * Tests if the view closes after cancellation.
+ */
+ @Test
+ public void cancellation() {
+ presenter.start();
+ presenter.cancelled();
- assertFalse(stub.isOpened());
- }
+ assertFalse(stub.isOpened());
+ }
}
diff --git a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
index 7bc0043e8..b81e44251 100644
--- a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
+++ b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
@@ -46,7 +46,7 @@ public class LoadBalancer {
Server server = servers.get(lastServedId++);
server.serve(request);
}
-
+
}
diff --git a/monostate/src/main/java/com/iluwatar/monostate/Request.java b/monostate/src/main/java/com/iluwatar/monostate/Request.java
index ee1f31d85..b18ba8ff2 100644
--- a/monostate/src/main/java/com/iluwatar/monostate/Request.java
+++ b/monostate/src/main/java/com/iluwatar/monostate/Request.java
@@ -2,7 +2,7 @@ package com.iluwatar.monostate;
/**
*
- * The Request class. A {@link Server} can handle an instance of a Request.
+ * The Request class. A {@link Server} can handle an instance of a Request.
*
*/
diff --git a/monostate/src/main/java/com/iluwatar/monostate/Server.java b/monostate/src/main/java/com/iluwatar/monostate/Server.java
index ce4e0222d..f48f4ad0f 100644
--- a/monostate/src/main/java/com/iluwatar/monostate/Server.java
+++ b/monostate/src/main/java/com/iluwatar/monostate/Server.java
@@ -2,8 +2,8 @@ package com.iluwatar.monostate;
/**
*
- * The Server class. Each Server sits behind a LoadBalancer which delegates the call to the
- * servers in a simplistic Round Robin fashion.
+ * The Server class. Each Server sits behind a LoadBalancer which delegates the call to the servers
+ * in a simplistic Round Robin fashion.
*
*/
public class Server {
@@ -26,6 +26,7 @@ public class Server {
}
public final void serve(Request request) {
- System.out.println("Server ID " + id + " associated to host : " + getHost() + " and Port " + getPort() +" Processed request with value " + request.value);
+ System.out.println("Server ID " + id + " associated to host : " + getHost() + " and Port "
+ + getPort() + " Processed request with value " + request.value);
}
}
diff --git a/monostate/src/test/java/com/iluwatar/monostate/AppTest.java b/monostate/src/test/java/com/iluwatar/monostate/AppTest.java
index c5f1f7e92..c502dd14a 100644
--- a/monostate/src/test/java/com/iluwatar/monostate/AppTest.java
+++ b/monostate/src/test/java/com/iluwatar/monostate/AppTest.java
@@ -15,7 +15,7 @@ public class AppTest {
// Both Should have the same LastServedId
Assert.assertTrue(balancer.getLastServedId() == balancer2.getLastServedId());
}
-
+
@Test
public void testMain() {
String[] args = {};
diff --git a/multiton/src/main/java/com/iluwatar/multiton/App.java b/multiton/src/main/java/com/iluwatar/multiton/App.java
index 9f2c5da78..273087310 100644
--- a/multiton/src/main/java/com/iluwatar/multiton/App.java
+++ b/multiton/src/main/java/com/iluwatar/multiton/App.java
@@ -2,31 +2,31 @@ package com.iluwatar.multiton;
/**
*
- * Whereas Singleton design pattern introduces single globally
- * accessible object the Multiton pattern defines many globally
- * accessible objects. The client asks for the correct instance
- * from the Multiton by passing an enumeration as parameter.
+ * Whereas Singleton design pattern introduces single globally accessible object the Multiton
+ * pattern defines many globally accessible objects. The client asks for the correct instance from
+ * the Multiton by passing an enumeration as parameter.
*
- * In this example {@link Nazgul} is the Multiton and we can ask single
- * {@link Nazgul} from it using {@link NazgulName}. The {@link Nazgul}s are statically
- * initialized and stored in concurrent hash map.
+ * In this example {@link Nazgul} is the Multiton and we can ask single {@link Nazgul} from it using
+ * {@link NazgulName}. The {@link Nazgul}s are statically initialized and stored in concurrent hash
+ * map.
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
- System.out.println("KHAMUL=" + Nazgul.getInstance(NazgulName.KHAMUL));
- System.out.println("MURAZOR=" + Nazgul.getInstance(NazgulName.MURAZOR));
- System.out.println("DWAR=" + Nazgul.getInstance(NazgulName.DWAR));
- System.out.println("JI_INDUR=" + Nazgul.getInstance(NazgulName.JI_INDUR));
- System.out.println("AKHORAHIL=" + Nazgul.getInstance(NazgulName.AKHORAHIL));
- System.out.println("HOARMURATH=" + Nazgul.getInstance(NazgulName.HOARMURATH));
- System.out.println("ADUNAPHEL=" + Nazgul.getInstance(NazgulName.ADUNAPHEL));
- System.out.println("REN=" + Nazgul.getInstance(NazgulName.REN));
- System.out.println("UVATHA=" + Nazgul.getInstance(NazgulName.UVATHA));
- }
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ System.out.println("KHAMUL=" + Nazgul.getInstance(NazgulName.KHAMUL));
+ System.out.println("MURAZOR=" + Nazgul.getInstance(NazgulName.MURAZOR));
+ System.out.println("DWAR=" + Nazgul.getInstance(NazgulName.DWAR));
+ System.out.println("JI_INDUR=" + Nazgul.getInstance(NazgulName.JI_INDUR));
+ System.out.println("AKHORAHIL=" + Nazgul.getInstance(NazgulName.AKHORAHIL));
+ System.out.println("HOARMURATH=" + Nazgul.getInstance(NazgulName.HOARMURATH));
+ System.out.println("ADUNAPHEL=" + Nazgul.getInstance(NazgulName.ADUNAPHEL));
+ System.out.println("REN=" + Nazgul.getInstance(NazgulName.REN));
+ System.out.println("UVATHA=" + Nazgul.getInstance(NazgulName.UVATHA));
+ }
}
diff --git a/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java b/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java
index 833923f75..f6f5ce84d 100644
--- a/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java
+++ b/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java
@@ -5,38 +5,37 @@ import java.util.concurrent.ConcurrentHashMap;
/**
*
- * Nazgul is a Multiton class. Nazgul instances can be queried
- * using {@link #getInstance} method.
+ * Nazgul is a Multiton class. Nazgul instances can be queried using {@link #getInstance} method.
*
*/
public class Nazgul {
- private static Map nazguls;
-
- private NazgulName name;
+ private static Map nazguls;
- static {
- nazguls = new ConcurrentHashMap<>();
- nazguls.put(NazgulName.KHAMUL, new Nazgul(NazgulName.KHAMUL));
- nazguls.put(NazgulName.MURAZOR, new Nazgul(NazgulName.MURAZOR));
- nazguls.put(NazgulName.DWAR, new Nazgul(NazgulName.DWAR));
- nazguls.put(NazgulName.JI_INDUR, new Nazgul(NazgulName.JI_INDUR));
- nazguls.put(NazgulName.AKHORAHIL, new Nazgul(NazgulName.AKHORAHIL));
- nazguls.put(NazgulName.HOARMURATH, new Nazgul(NazgulName.HOARMURATH));
- nazguls.put(NazgulName.ADUNAPHEL, new Nazgul(NazgulName.ADUNAPHEL));
- nazguls.put(NazgulName.REN, new Nazgul(NazgulName.REN));
- nazguls.put(NazgulName.UVATHA, new Nazgul(NazgulName.UVATHA));
- }
-
- private Nazgul(NazgulName name) {
- this.name = name;
- }
+ private NazgulName name;
- public static Nazgul getInstance(NazgulName name) {
- return nazguls.get(name);
- }
-
- public NazgulName getName() {
- return name;
- }
+ static {
+ nazguls = new ConcurrentHashMap<>();
+ nazguls.put(NazgulName.KHAMUL, new Nazgul(NazgulName.KHAMUL));
+ nazguls.put(NazgulName.MURAZOR, new Nazgul(NazgulName.MURAZOR));
+ nazguls.put(NazgulName.DWAR, new Nazgul(NazgulName.DWAR));
+ nazguls.put(NazgulName.JI_INDUR, new Nazgul(NazgulName.JI_INDUR));
+ nazguls.put(NazgulName.AKHORAHIL, new Nazgul(NazgulName.AKHORAHIL));
+ nazguls.put(NazgulName.HOARMURATH, new Nazgul(NazgulName.HOARMURATH));
+ nazguls.put(NazgulName.ADUNAPHEL, new Nazgul(NazgulName.ADUNAPHEL));
+ nazguls.put(NazgulName.REN, new Nazgul(NazgulName.REN));
+ nazguls.put(NazgulName.UVATHA, new Nazgul(NazgulName.UVATHA));
+ }
+
+ private Nazgul(NazgulName name) {
+ this.name = name;
+ }
+
+ public static Nazgul getInstance(NazgulName name) {
+ return nazguls.get(name);
+ }
+
+ public NazgulName getName() {
+ return name;
+ }
}
diff --git a/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java b/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java
index cef1e43a9..8869042df 100644
--- a/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java
+++ b/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java
@@ -7,6 +7,6 @@ package com.iluwatar.multiton;
*/
public enum NazgulName {
- KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA;
-
+ KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA;
+
}
diff --git a/multiton/src/test/java/com/iluwatar/multiton/AppTest.java b/multiton/src/test/java/com/iluwatar/multiton/AppTest.java
index 439f08e24..41b1387a6 100644
--- a/multiton/src/test/java/com/iluwatar/multiton/AppTest.java
+++ b/multiton/src/test/java/com/iluwatar/multiton/AppTest.java
@@ -10,10 +10,10 @@ import com.iluwatar.multiton.App;
*
*/
public class AppTest {
-
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageService.java b/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageService.java
index 641c39ae7..6769f95dd 100644
--- a/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageService.java
+++ b/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageService.java
@@ -1,20 +1,16 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.dom.app.homepage;
@@ -25,27 +21,25 @@ import org.apache.isis.applib.annotation.HomePage;
import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.annotation.SemanticsOf;
-@DomainService(
- nature = NatureOfService.VIEW_CONTRIBUTIONS_ONLY // trick to suppress the actions from the top-level menu
+@DomainService(nature = NatureOfService.VIEW_CONTRIBUTIONS_ONLY // trick to suppress the actions
+ // from the top-level menu
)
public class HomePageService {
- //region > homePage (action)
+ // region > homePage (action)
- @Action(
- semantics = SemanticsOf.SAFE
- )
- @HomePage
- public HomePageViewModel homePage() {
- return container.injectServicesInto(new HomePageViewModel());
- }
+ @Action(semantics = SemanticsOf.SAFE)
+ @HomePage
+ public HomePageViewModel homePage() {
+ return container.injectServicesInto(new HomePageViewModel());
+ }
- //endregion
+ // endregion
- //region > injected services
+ // region > injected services
- @javax.inject.Inject
- DomainObjectContainer container;
+ @javax.inject.Inject
+ DomainObjectContainer container;
- //endregion
+ // endregion
}
diff --git a/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageViewModel.java b/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageViewModel.java
index 83015d057..1391bac6a 100644
--- a/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageViewModel.java
+++ b/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageViewModel.java
@@ -1,20 +1,16 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.dom.app.homepage;
@@ -28,23 +24,25 @@ import domainapp.dom.modules.simple.SimpleObjects;
@ViewModel
public class HomePageViewModel {
- //region > title
- public String title() {
- return getObjects().size() + " objects";
- }
- //endregion
+ // region > title
+ public String title() {
+ return getObjects().size() + " objects";
+ }
- //region > object (collection)
- @org.apache.isis.applib.annotation.HomePage
- public List getObjects() {
- return simpleObjects.listAll();
- }
- //endregion
+ // endregion
- //region > injected services
+ // region > object (collection)
+ @org.apache.isis.applib.annotation.HomePage
+ public List getObjects() {
+ return simpleObjects.listAll();
+ }
- @javax.inject.Inject
- SimpleObjects simpleObjects;
+ // endregion
- //endregion
+ // region > injected services
+
+ @javax.inject.Inject
+ SimpleObjects simpleObjects;
+
+ // endregion
}
diff --git a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.java b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.java
index a4fba6dda..300e184fa 100644
--- a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.java
+++ b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.java
@@ -1,20 +1,16 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.dom.modules.simple;
@@ -37,113 +33,95 @@ import org.apache.isis.applib.services.eventbus.ActionDomainEvent;
import org.apache.isis.applib.services.i18n.TranslatableString;
import org.apache.isis.applib.util.ObjectContracts;
-@javax.jdo.annotations.PersistenceCapable(
- identityType=IdentityType.DATASTORE,
- schema = "simple",
- table = "SimpleObject"
-)
+@javax.jdo.annotations.PersistenceCapable(identityType = IdentityType.DATASTORE, schema = "simple",
+ table = "SimpleObject")
@javax.jdo.annotations.DatastoreIdentity(
- strategy=javax.jdo.annotations.IdGeneratorStrategy.IDENTITY,
- column="id")
-@javax.jdo.annotations.Version(
- strategy=VersionStrategy.VERSION_NUMBER,
- column="version")
+ strategy = javax.jdo.annotations.IdGeneratorStrategy.IDENTITY, column = "id")
+@javax.jdo.annotations.Version(strategy = VersionStrategy.VERSION_NUMBER, column = "version")
@javax.jdo.annotations.Queries({
- @javax.jdo.annotations.Query(
- name = "find", language = "JDOQL",
- value = "SELECT "
- + "FROM domainapp.dom.modules.simple.SimpleObject "),
- @javax.jdo.annotations.Query(
- name = "findByName", language = "JDOQL",
- value = "SELECT "
- + "FROM domainapp.dom.modules.simple.SimpleObject "
- + "WHERE name.indexOf(:name) >= 0 ")
-})
-@javax.jdo.annotations.Unique(name="SimpleObject_name_UNQ", members = {"name"})
+ @javax.jdo.annotations.Query(name = "find", language = "JDOQL", value = "SELECT "
+ + "FROM domainapp.dom.modules.simple.SimpleObject "),
+ @javax.jdo.annotations.Query(name = "findByName", language = "JDOQL", value = "SELECT "
+ + "FROM domainapp.dom.modules.simple.SimpleObject " + "WHERE name.indexOf(:name) >= 0 ")})
+@javax.jdo.annotations.Unique(name = "SimpleObject_name_UNQ", members = {"name"})
@DomainObject
-@DomainObjectLayout(
- bookmarking = BookmarkPolicy.AS_ROOT,
- cssClassFa = "fa-flag"
-)
+@DomainObjectLayout(bookmarking = BookmarkPolicy.AS_ROOT, cssClassFa = "fa-flag")
public class SimpleObject implements Comparable {
- //region > identificatiom
- public TranslatableString title() {
- return TranslatableString.tr("Object: {name}", "name", getName());
+ // region > identificatiom
+ public TranslatableString title() {
+ return TranslatableString.tr("Object: {name}", "name", getName());
+ }
+
+ // endregion
+
+ // region > name (property)
+
+ private String name;
+
+ @javax.jdo.annotations.Column(allowsNull = "false", length = 40)
+ @Title(sequence = "1")
+ @Property(editing = Editing.DISABLED)
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ // endregion
+
+ // region > updateName (action)
+
+ public static class UpdateNameDomainEvent extends ActionDomainEvent {
+ public UpdateNameDomainEvent(final SimpleObject source, final Identifier identifier,
+ final Object... arguments) {
+ super(source, identifier, arguments);
}
- //endregion
+ }
- //region > name (property)
+ @Action(domainEvent = UpdateNameDomainEvent.class)
+ public SimpleObject updateName(
+ @Parameter(maxLength = 40) @ParameterLayout(named = "New name") final String name) {
+ setName(name);
+ return this;
+ }
- private String name;
+ public String default0UpdateName() {
+ return getName();
+ }
- @javax.jdo.annotations.Column(allowsNull="false", length = 40)
- @Title(sequence="1")
- @Property(
- editing = Editing.DISABLED
- )
- public String getName() {
- return name;
- }
+ public TranslatableString validateUpdateName(final String name) {
+ return name.contains("!") ? TranslatableString.tr("Exclamation mark is not allowed") : null;
+ }
- public void setName(final String name) {
- this.name = name;
- }
+ // endregion
- // endregion
+ // region > version (derived property)
+ public Long getVersionSequence() {
+ return (Long) JDOHelper.getVersion(this);
+ }
- //region > updateName (action)
+ // endregion
- public static class UpdateNameDomainEvent extends ActionDomainEvent {
- public UpdateNameDomainEvent(final SimpleObject source, final Identifier identifier, final Object... arguments) {
- super(source, identifier, arguments);
- }
- }
+ // region > compareTo
- @Action(
- domainEvent = UpdateNameDomainEvent.class
- )
- public SimpleObject updateName(
- @Parameter(maxLength = 40)
- @ParameterLayout(named = "New name")
- final String name) {
- setName(name);
- return this;
- }
+ @Override
+ public int compareTo(final SimpleObject other) {
+ return ObjectContracts.compare(this, other, "name");
+ }
- public String default0UpdateName() {
- return getName();
- }
+ // endregion
- public TranslatableString validateUpdateName(final String name) {
- return name.contains("!")? TranslatableString.tr("Exclamation mark is not allowed"): null;
- }
+ // region > injected services
- //endregion
+ @javax.inject.Inject
+ @SuppressWarnings("unused")
+ private DomainObjectContainer container;
- //region > version (derived property)
- public Long getVersionSequence() {
- return (Long) JDOHelper.getVersion(this);
- }
- //endregion
-
- //region > compareTo
-
- @Override
- public int compareTo(final SimpleObject other) {
- return ObjectContracts.compare(this, other, "name");
- }
-
- //endregion
-
- //region > injected services
-
- @javax.inject.Inject
- @SuppressWarnings("unused")
- private DomainObjectContainer container;
-
- //endregion
+ // endregion
}
diff --git a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObjects.java b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObjects.java
index 0634dd16a..5e4642455 100644
--- a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObjects.java
+++ b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObjects.java
@@ -1,20 +1,16 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.dom.modules.simple;
@@ -38,70 +34,56 @@ import org.apache.isis.applib.services.i18n.TranslatableString;
@DomainServiceLayout(menuOrder = "10")
public class SimpleObjects {
- //region > title
- public TranslatableString title() {
- return TranslatableString.tr("Simple Objects");
+ // region > title
+ public TranslatableString title() {
+ return TranslatableString.tr("Simple Objects");
+ }
+
+ // endregion
+
+ // region > listAll (action)
+ @Action(semantics = SemanticsOf.SAFE)
+ @ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT)
+ @MemberOrder(sequence = "1")
+ public List listAll() {
+ return container.allInstances(SimpleObject.class);
+ }
+
+ // endregion
+
+ // region > findByName (action)
+ @Action(semantics = SemanticsOf.SAFE)
+ @ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT)
+ @MemberOrder(sequence = "2")
+ public List findByName(@ParameterLayout(named = "Name") final String name) {
+ return container.allMatches(new QueryDefault<>(SimpleObject.class, "findByName", "name", name));
+ }
+
+ // endregion
+
+ // region > create (action)
+ public static class CreateDomainEvent extends ActionDomainEvent {
+ public CreateDomainEvent(final SimpleObjects source, final Identifier identifier,
+ final Object... arguments) {
+ super(source, identifier, arguments);
}
- //endregion
+ }
- //region > listAll (action)
- @Action(
- semantics = SemanticsOf.SAFE
- )
- @ActionLayout(
- bookmarking = BookmarkPolicy.AS_ROOT
- )
- @MemberOrder(sequence = "1")
- public List listAll() {
- return container.allInstances(SimpleObject.class);
- }
- //endregion
+ @Action(domainEvent = CreateDomainEvent.class)
+ @MemberOrder(sequence = "3")
+ public SimpleObject create(final @ParameterLayout(named = "Name") String name) {
+ final SimpleObject obj = container.newTransientInstance(SimpleObject.class);
+ obj.setName(name);
+ container.persistIfNotAlready(obj);
+ return obj;
+ }
- //region > findByName (action)
- @Action(
- semantics = SemanticsOf.SAFE
- )
- @ActionLayout(
- bookmarking = BookmarkPolicy.AS_ROOT
- )
- @MemberOrder(sequence = "2")
- public List findByName(
- @ParameterLayout(named="Name")
- final String name
- ) {
- return container.allMatches(
- new QueryDefault<>(
- SimpleObject.class,
- "findByName",
- "name", name));
- }
- //endregion
+ // endregion
- //region > create (action)
- public static class CreateDomainEvent extends ActionDomainEvent {
- public CreateDomainEvent(final SimpleObjects source, final Identifier identifier, final Object... arguments) {
- super(source, identifier, arguments);
- }
- }
+ // region > injected services
- @Action(
- domainEvent = CreateDomainEvent.class
- )
- @MemberOrder(sequence = "3")
- public SimpleObject create(
- final @ParameterLayout(named="Name") String name) {
- final SimpleObject obj = container.newTransientInstance(SimpleObject.class);
- obj.setName(name);
- container.persistIfNotAlready(obj);
- return obj;
- }
+ @javax.inject.Inject
+ DomainObjectContainer container;
- //endregion
-
- //region > injected services
-
- @javax.inject.Inject
- DomainObjectContainer container;
-
- //endregion
+ // endregion
}
diff --git a/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectTest.java b/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectTest.java
index e29b3f246..fc62239c2 100644
--- a/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectTest.java
+++ b/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectTest.java
@@ -1,18 +1,16 @@
/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.dom.modules.simple;
@@ -23,27 +21,27 @@ import static org.assertj.core.api.Assertions.assertThat;
public class SimpleObjectTest {
- SimpleObject simpleObject;
+ SimpleObject simpleObject;
- @Before
- public void setUp() throws Exception {
- simpleObject = new SimpleObject();
- }
-
- public static class Name extends SimpleObjectTest {
-
- @Test
- public void happyCase() throws Exception {
- // given
- String name = "Foobar";
- assertThat(simpleObject.getName()).isNull();
-
- // when
- simpleObject.setName(name);
-
- // then
- assertThat(simpleObject.getName()).isEqualTo(name);
- }
+ @Before
+ public void setUp() throws Exception {
+ simpleObject = new SimpleObject();
+ }
+
+ public static class Name extends SimpleObjectTest {
+
+ @Test
+ public void happyCase() throws Exception {
+ // given
+ String name = "Foobar";
+ assertThat(simpleObject.getName()).isNull();
+
+ // when
+ simpleObject.setName(name);
+
+ // then
+ assertThat(simpleObject.getName()).isEqualTo(name);
}
+ }
}
diff --git a/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectsTest.java b/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectsTest.java
index a41d25ad9..47cad61b8 100644
--- a/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectsTest.java
+++ b/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectsTest.java
@@ -1,18 +1,16 @@
/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.dom.modules.simple;
@@ -35,70 +33,70 @@ import static org.assertj.core.api.Assertions.assertThat;
public class SimpleObjectsTest {
- @Rule
- public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(Mode.INTERFACES_AND_CLASSES);
+ @Rule
+ public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(Mode.INTERFACES_AND_CLASSES);
- @Mock
- DomainObjectContainer mockContainer;
-
- SimpleObjects simpleObjects;
+ @Mock
+ DomainObjectContainer mockContainer;
- @Before
- public void setUp() throws Exception {
- simpleObjects = new SimpleObjects();
- simpleObjects.container = mockContainer;
- }
+ SimpleObjects simpleObjects;
- public static class Create extends SimpleObjectsTest {
+ @Before
+ public void setUp() throws Exception {
+ simpleObjects = new SimpleObjects();
+ simpleObjects.container = mockContainer;
+ }
- @Test
- public void happyCase() throws Exception {
+ public static class Create extends SimpleObjectsTest {
- // given
- final SimpleObject simpleObject = new SimpleObject();
+ @Test
+ public void happyCase() throws Exception {
- final Sequence seq = context.sequence("create");
- context.checking(new Expectations() {
- {
- oneOf(mockContainer).newTransientInstance(SimpleObject.class);
- inSequence(seq);
- will(returnValue(simpleObject));
+ // given
+ final SimpleObject simpleObject = new SimpleObject();
- oneOf(mockContainer).persistIfNotAlready(simpleObject);
- inSequence(seq);
- }
- });
+ final Sequence seq = context.sequence("create");
+ context.checking(new Expectations() {
+ {
+ oneOf(mockContainer).newTransientInstance(SimpleObject.class);
+ inSequence(seq);
+ will(returnValue(simpleObject));
- // when
- final SimpleObject obj = simpleObjects.create("Foobar");
-
- // then
- assertThat(obj).isEqualTo(simpleObject);
- assertThat(obj.getName()).isEqualTo("Foobar");
+ oneOf(mockContainer).persistIfNotAlready(simpleObject);
+ inSequence(seq);
}
+ });
+ // when
+ final SimpleObject obj = simpleObjects.create("Foobar");
+
+ // then
+ assertThat(obj).isEqualTo(simpleObject);
+ assertThat(obj.getName()).isEqualTo("Foobar");
}
- public static class ListAll extends SimpleObjectsTest {
+ }
- @Test
- public void happyCase() throws Exception {
+ public static class ListAll extends SimpleObjectsTest {
- // given
- final List all = Lists.newArrayList();
+ @Test
+ public void happyCase() throws Exception {
- context.checking(new Expectations() {
- {
- oneOf(mockContainer).allInstances(SimpleObject.class);
- will(returnValue(all));
- }
- });
+ // given
+ final List all = Lists.newArrayList();
- // when
- final List list = simpleObjects.listAll();
-
- // then
- assertThat(list).isEqualTo(all);
+ context.checking(new Expectations() {
+ {
+ oneOf(mockContainer).allInstances(SimpleObject.class);
+ will(returnValue(all));
}
+ });
+
+ // when
+ final List list = simpleObjects.listAll();
+
+ // then
+ assertThat(list).isEqualTo(all);
}
+ }
}
diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/DomainAppFixturesProvider.java b/naked-objects/fixture/src/main/java/domainapp/fixture/DomainAppFixturesProvider.java
index ab6b6b4be..ccc11f2b8 100644
--- a/naked-objects/fixture/src/main/java/domainapp/fixture/DomainAppFixturesProvider.java
+++ b/naked-objects/fixture/src/main/java/domainapp/fixture/DomainAppFixturesProvider.java
@@ -1,20 +1,16 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.fixture;
@@ -31,14 +27,12 @@ import domainapp.fixture.scenarios.RecreateSimpleObjects;
*/
@DomainService(nature = NatureOfService.DOMAIN)
public class DomainAppFixturesProvider implements FixtureScriptsSpecificationProvider {
- @Override
- public FixtureScriptsSpecification getSpecification() {
- return FixtureScriptsSpecification
- .builder(DomainAppFixturesProvider.class)
- .with(FixtureScripts.MultipleExecutionStrategy.EXECUTE)
- .withRunScriptDefault(RecreateSimpleObjects.class)
- .withRunScriptDropDown(FixtureScriptsSpecification.DropDownPolicy.CHOICES)
- .withRecreate(RecreateSimpleObjects.class)
- .build();
- }
+ @Override
+ public FixtureScriptsSpecification getSpecification() {
+ return FixtureScriptsSpecification.builder(DomainAppFixturesProvider.class)
+ .with(FixtureScripts.MultipleExecutionStrategy.EXECUTE)
+ .withRunScriptDefault(RecreateSimpleObjects.class)
+ .withRunScriptDropDown(FixtureScriptsSpecification.DropDownPolicy.CHOICES)
+ .withRecreate(RecreateSimpleObjects.class).build();
+ }
}
diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java
index 926217d09..2918fe7f6 100644
--- a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java
+++ b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java
@@ -1,20 +1,16 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.fixture.modules.simple;
@@ -26,46 +22,50 @@ import domainapp.dom.modules.simple.SimpleObjects;
public class SimpleObjectCreate extends FixtureScript {
- //region > name (input)
- private String name;
- /**
- * Name of the object (required)
- */
- public String getName() {
- return name;
- }
+ // region > name (input)
+ private String name;
- public SimpleObjectCreate setName(final String name) {
- this.name = name;
- return this;
- }
- //endregion
+ /**
+ * Name of the object (required)
+ */
+ public String getName() {
+ return name;
+ }
+
+ public SimpleObjectCreate setName(final String name) {
+ this.name = name;
+ return this;
+ }
+
+ // endregion
- //region > simpleObject (output)
- private SimpleObject simpleObject;
+ // region > simpleObject (output)
+ private SimpleObject simpleObject;
- /**
- * The created simple object (output).
- * @return
- */
- public SimpleObject getSimpleObject() {
- return simpleObject;
- }
- //endregion
+ /**
+ * The created simple object (output).
+ *
+ * @return
+ */
+ public SimpleObject getSimpleObject() {
+ return simpleObject;
+ }
- @Override
- protected void execute(final ExecutionContext ec) {
+ // endregion
- String name = checkParam("name", ec, String.class);
+ @Override
+ protected void execute(final ExecutionContext ec) {
- this.simpleObject = wrap(simpleObjects).create(name);
+ String name = checkParam("name", ec, String.class);
- // also make available to UI
- ec.addResult(this, simpleObject);
- }
+ this.simpleObject = wrap(simpleObjects).create(name);
- @javax.inject.Inject
- private SimpleObjects simpleObjects;
+ // also make available to UI
+ ec.addResult(this, simpleObject);
+ }
+
+ @javax.inject.Inject
+ private SimpleObjects simpleObjects;
}
diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectsTearDown.java b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectsTearDown.java
index cc06eb4ac..e844af9c7 100644
--- a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectsTearDown.java
+++ b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectsTearDown.java
@@ -1,20 +1,16 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.fixture.modules.simple;
@@ -24,13 +20,13 @@ import org.apache.isis.applib.services.jdosupport.IsisJdoSupport;
public class SimpleObjectsTearDown extends FixtureScript {
- @Override
- protected void execute(ExecutionContext executionContext) {
- isisJdoSupport.executeUpdate("delete from \"simple\".\"SimpleObject\"");
- }
+ @Override
+ protected void execute(ExecutionContext executionContext) {
+ isisJdoSupport.executeUpdate("delete from \"simple\".\"SimpleObject\"");
+ }
- @javax.inject.Inject
- private IsisJdoSupport isisJdoSupport;
+ @javax.inject.Inject
+ private IsisJdoSupport isisJdoSupport;
}
diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java b/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java
index 072769e29..c978e0b82 100644
--- a/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java
+++ b/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java
@@ -1,20 +1,16 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.fixture.scenarios;
@@ -33,60 +29,63 @@ import domainapp.fixture.modules.simple.SimpleObjectsTearDown;
public class RecreateSimpleObjects extends FixtureScript {
- public final List NAMES = Collections.unmodifiableList(Arrays.asList(
- "Foo", "Bar", "Baz", "Frodo", "Froyo", "Fizz", "Bip", "Bop", "Bang", "Boo"));
+ public final List NAMES = Collections.unmodifiableList(Arrays.asList("Foo", "Bar", "Baz",
+ "Frodo", "Froyo", "Fizz", "Bip", "Bop", "Bang", "Boo"));
- public RecreateSimpleObjects() {
- withDiscoverability(Discoverability.DISCOVERABLE);
+ public RecreateSimpleObjects() {
+ withDiscoverability(Discoverability.DISCOVERABLE);
+ }
+
+ // region > number (optional input)
+ private Integer number;
+
+ /**
+ * The number of objects to create, up to 10; optional, defaults to 3.
+ */
+ public Integer getNumber() {
+ return number;
+ }
+
+ public RecreateSimpleObjects setNumber(final Integer number) {
+ this.number = number;
+ return this;
+ }
+
+ // endregion
+
+ // region > simpleObjects (output)
+ private final List simpleObjects = Lists.newArrayList();
+
+ /**
+ * The simpleobjects created by this fixture (output).
+ */
+ public List getSimpleObjects() {
+ return simpleObjects;
+ }
+
+ // endregion
+
+ @Override
+ protected void execute(final ExecutionContext ec) {
+
+ // defaults
+ final int number = defaultParam("number", ec, 3);
+
+ // validate
+ if (number < 0 || number > NAMES.size()) {
+ throw new IllegalArgumentException(String.format("number must be in range [0,%d)",
+ NAMES.size()));
}
- //region > number (optional input)
- private Integer number;
+ //
+ // execute
+ //
+ ec.executeChild(this, new SimpleObjectsTearDown());
- /**
- * The number of objects to create, up to 10; optional, defaults to 3.
- */
- public Integer getNumber() {
- return number;
- }
-
- public RecreateSimpleObjects setNumber(final Integer number) {
- this.number = number;
- return this;
- }
- //endregion
-
- //region > simpleObjects (output)
- private final List simpleObjects = Lists.newArrayList();
-
- /**
- * The simpleobjects created by this fixture (output).
- */
- public List getSimpleObjects() {
- return simpleObjects;
- }
- //endregion
-
- @Override
- protected void execute(final ExecutionContext ec) {
-
- // defaults
- final int number = defaultParam("number", ec, 3);
-
- // validate
- if(number < 0 || number > NAMES.size()) {
- throw new IllegalArgumentException(String.format("number must be in range [0,%d)", NAMES.size()));
- }
-
- //
- // execute
- //
- ec.executeChild(this, new SimpleObjectsTearDown());
-
- for (int i = 0; i < number; i++) {
- final SimpleObjectCreate fs = new SimpleObjectCreate().setName(NAMES.get(i));
- ec.executeChild(this, fs.getName(), fs);
- simpleObjects.add(fs.getSimpleObject());
- }
+ for (int i = 0; i < number; i++) {
+ final SimpleObjectCreate fs = new SimpleObjectCreate().setName(NAMES.get(i));
+ ec.executeChild(this, fs.getName(), fs);
+ simpleObjects.add(fs.getSimpleObject());
}
+ }
}
diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java b/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java
index 28e9d3786..c617915f1 100644
--- a/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java
+++ b/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java
@@ -1,20 +1,16 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.integtests.bootstrap;
@@ -25,30 +21,31 @@ import org.apache.isis.objectstore.jdo.datanucleus.IsisConfigurationForJdoIntegT
public class SimpleAppSystemInitializer {
- public static void initIsft() {
- IsisSystemForTest isft = IsisSystemForTest.getElseNull();
- if(isft == null) {
- isft = new SimpleAppSystemBuilder().build().setUpSystem();
- IsisSystemForTest.set(isft);
- }
+ public static void initIsft() {
+ IsisSystemForTest isft = IsisSystemForTest.getElseNull();
+ if (isft == null) {
+ isft = new SimpleAppSystemBuilder().build().setUpSystem();
+ IsisSystemForTest.set(isft);
+ }
+ }
+
+ private static class SimpleAppSystemBuilder extends IsisSystemForTest.Builder {
+
+ public SimpleAppSystemBuilder() {
+ withLoggingAt(org.apache.log4j.Level.INFO);
+ with(testConfiguration());
+ with(new DataNucleusPersistenceMechanismInstaller());
+
+ // services annotated with @DomainService
+ withServicesIn("domainapp");
}
- private static class SimpleAppSystemBuilder extends IsisSystemForTest.Builder {
+ private static IsisConfiguration testConfiguration() {
+ final IsisConfigurationForJdoIntegTests testConfiguration =
+ new IsisConfigurationForJdoIntegTests();
- public SimpleAppSystemBuilder() {
- withLoggingAt(org.apache.log4j.Level.INFO);
- with(testConfiguration());
- with(new DataNucleusPersistenceMechanismInstaller());
-
- // services annotated with @DomainService
- withServicesIn( "domainapp" );
- }
-
- private static IsisConfiguration testConfiguration() {
- final IsisConfigurationForJdoIntegTests testConfiguration = new IsisConfigurationForJdoIntegTests();
-
- testConfiguration.addRegisterEntitiesPackagePrefix("domainapp.dom.modules");
- return testConfiguration;
- }
+ testConfiguration.addRegisterEntitiesPackagePrefix("domainapp.dom.modules");
+ return testConfiguration;
}
+ }
}
diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/BootstrappingGlue.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/BootstrappingGlue.java
index b175d4744..190e1f5bb 100644
--- a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/BootstrappingGlue.java
+++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/BootstrappingGlue.java
@@ -1,18 +1,16 @@
/**
-O * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * O * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.integtests.specglue;
@@ -25,17 +23,17 @@ import domainapp.integtests.bootstrap.SimpleAppSystemInitializer;
public class BootstrappingGlue extends CukeGlueAbstract {
- @Before(value={"@integration"}, order=100)
- public void beforeScenarioIntegrationScope() {
- org.apache.log4j.PropertyConfigurator.configure("logging.properties");
- SimpleAppSystemInitializer.initIsft();
-
- before(ScenarioExecutionScope.INTEGRATION);
- }
+ @Before(value = {"@integration"}, order = 100)
+ public void beforeScenarioIntegrationScope() {
+ org.apache.log4j.PropertyConfigurator.configure("logging.properties");
+ SimpleAppSystemInitializer.initIsft();
- @After
- public void afterScenario(cucumber.api.Scenario sc) {
- assertMocksSatisfied();
- after(sc);
- }
+ before(ScenarioExecutionScope.INTEGRATION);
+ }
+
+ @After
+ public void afterScenario(cucumber.api.Scenario sc) {
+ assertMocksSatisfied();
+ after(sc);
+ }
}
diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java
index a2d5c8985..2fcb7cca7 100644
--- a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java
+++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java
@@ -1,18 +1,16 @@
/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.integtests.specglue;
@@ -23,9 +21,8 @@ import domainapp.fixture.scenarios.RecreateSimpleObjects;
public class CatalogOfFixturesGlue extends CukeGlueAbstract {
- @Before(value={"@integration", "@SimpleObjectsFixture"}, order=20000)
- public void integrationFixtures() throws Throwable {
- scenarioExecution().install(new RecreateSimpleObjects());
- }
-
+ @Before(value = {"@integration", "@SimpleObjectsFixture"}, order = 20000)
+ public void integrationFixtures() throws Throwable {
+ scenarioExecution().install(new RecreateSimpleObjects());
+ }
}
diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java
index 63d96bd53..ef6012919 100644
--- a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java
+++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java
@@ -1,18 +1,16 @@
/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.integtests.specglue.modules.simple;
@@ -30,21 +28,21 @@ import static org.junit.Assert.assertThat;
public class SimpleObjectGlue extends CukeGlueAbstract {
- @Given("^there are.* (\\d+) simple objects$")
- public void there_are_N_simple_objects(int n) throws Throwable {
- try {
- final List findAll = service(SimpleObjects.class).listAll();
- assertThat(findAll.size(), is(n));
- putVar("list", "all", findAll);
-
- } finally {
- assertMocksSatisfied();
- }
+ @Given("^there are.* (\\d+) simple objects$")
+ public void there_are_N_simple_objects(int n) throws Throwable {
+ try {
+ final List findAll = service(SimpleObjects.class).listAll();
+ assertThat(findAll.size(), is(n));
+ putVar("list", "all", findAll);
+
+ } finally {
+ assertMocksSatisfied();
}
-
- @When("^I create a new simple object$")
- public void I_create_a_new_simple_object() throws Throwable {
- service(SimpleObjects.class).create(UUID.randomUUID().toString());
- }
-
+ }
+
+ @When("^I create a new simple object$")
+ public void I_create_a_new_simple_object() throws Throwable {
+ service(SimpleObjects.class).create(UUID.randomUUID().toString());
+ }
+
}
diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specs/RunSpecs.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specs/RunSpecs.java
index 910b5a826..8a842a0f3 100644
--- a/naked-objects/integtests/src/test/java/domainapp/integtests/specs/RunSpecs.java
+++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specs/RunSpecs.java
@@ -1,18 +1,16 @@
/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.integtests.specs;
@@ -23,17 +21,12 @@ import cucumber.api.junit.Cucumber;
/**
- * Runs scenarios in all .feature files (this package and any subpackages).
+ * Runs scenarios in all .feature files (this package and any subpackages).
*/
@RunWith(Cucumber.class)
-@CucumberOptions(
- format = {
- "html:target/cucumber-html-report"
- ,"json:target/cucumber.json"
- },
- glue={"classpath:domainapp.integtests.specglue"},
- strict = true,
- tags = { "~@backlog", "~@ignore" })
+@CucumberOptions(format = {"html:target/cucumber-html-report", "json:target/cucumber.json"},
+ glue = {"classpath:domainapp.integtests.specglue"}, strict = true, tags = {"~@backlog",
+ "~@ignore"})
public class RunSpecs {
- // intentionally empty
+ // intentionally empty
}
diff --git a/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java b/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java
index 57d1e0ba1..c7bbd8c80 100644
--- a/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java
+++ b/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java
@@ -1,20 +1,16 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
*/
package domainapp.webapp;
@@ -53,6 +49,7 @@ import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchThemeProvid
*
*
* See:
+ *
*
* <filter>
* <filter-name>wicket</filter-name>
@@ -67,87 +64,96 @@ import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchThemeProvid
*/
public class SimpleApplication extends IsisWicketApplication {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- /**
- * uncomment for a (slightly hacky) way of allowing logins using query args, eg:
- *
- * ?user=sven&pass=pass
- *
- *
- * for demos only, obvious.
- */
- private final static boolean DEMO_MODE_USING_CREDENTIALS_AS_QUERYARGS = false;
+ /**
+ * uncomment for a (slightly hacky) way of allowing logins using query args, eg:
+ *
+ * ?user=sven&pass=pass
+ *
+ *
+ * for demos only, obvious.
+ */
+ private final static boolean DEMO_MODE_USING_CREDENTIALS_AS_QUERYARGS = false;
- @Override
- protected void init() {
- super.init();
+ @Override
+ protected void init() {
+ super.init();
- IBootstrapSettings settings = Bootstrap.getSettings();
- settings.setThemeProvider(new BootswatchThemeProvider(BootswatchTheme.Flatly));
+ IBootstrapSettings settings = Bootstrap.getSettings();
+ settings.setThemeProvider(new BootswatchThemeProvider(BootswatchTheme.Flatly));
+ }
+
+ @Override
+ public Session newSession(final Request request, final Response response) {
+ if (!DEMO_MODE_USING_CREDENTIALS_AS_QUERYARGS) {
+ return super.newSession(request, response);
}
- @Override
- public Session newSession(final Request request, final Response response) {
- if(!DEMO_MODE_USING_CREDENTIALS_AS_QUERYARGS) {
- return super.newSession(request, response);
- }
-
- // else demo mode
- final AuthenticatedWebSessionForIsis s = (AuthenticatedWebSessionForIsis) super.newSession(request, response);
- IRequestParameters requestParameters = request.getRequestParameters();
- final org.apache.wicket.util.string.StringValue user = requestParameters.getParameterValue("user");
- final org.apache.wicket.util.string.StringValue password = requestParameters.getParameterValue("pass");
- s.signIn(user.toString(), password.toString());
- return s;
+ // else demo mode
+ final AuthenticatedWebSessionForIsis s =
+ (AuthenticatedWebSessionForIsis) super.newSession(request, response);
+ IRequestParameters requestParameters = request.getRequestParameters();
+ final org.apache.wicket.util.string.StringValue user =
+ requestParameters.getParameterValue("user");
+ final org.apache.wicket.util.string.StringValue password =
+ requestParameters.getParameterValue("pass");
+ s.signIn(user.toString(), password.toString());
+ return s;
+ }
+
+ @Override
+ public WebRequest newWebRequest(HttpServletRequest servletRequest, String filterPath) {
+ if (!DEMO_MODE_USING_CREDENTIALS_AS_QUERYARGS) {
+ return super.newWebRequest(servletRequest, filterPath);
}
- @Override
- public WebRequest newWebRequest(HttpServletRequest servletRequest, String filterPath) {
- if(!DEMO_MODE_USING_CREDENTIALS_AS_QUERYARGS) {
- return super.newWebRequest(servletRequest, filterPath);
- }
-
- // else demo mode
- try {
- String uname = servletRequest.getParameter("user");
- if (uname != null) {
- servletRequest.getSession().invalidate();
- }
- } catch (Exception e) {
- }
- WebRequest request = super.newWebRequest(servletRequest, filterPath);
- return request;
+ // else demo mode
+ try {
+ String uname = servletRequest.getParameter("user");
+ if (uname != null) {
+ servletRequest.getSession().invalidate();
+ }
+ } catch (Exception e) {
}
-
- @Override
- protected Module newIsisWicketModule() {
- final Module isisDefaults = super.newIsisWicketModule();
-
- final Module overrides = new AbstractModule() {
- @Override
- protected void configure() {
- bind(String.class).annotatedWith(Names.named("applicationName")).toInstance("Simple App");
- bind(String.class).annotatedWith(Names.named("applicationCss")).toInstance("css/application.css");
- bind(String.class).annotatedWith(Names.named("applicationJs")).toInstance("scripts/application.js");
- bind(String.class).annotatedWith(Names.named("welcomeMessage")).toInstance(readLines(getClass(), "welcome.html"));
- bind(String.class).annotatedWith(Names.named("aboutMessage")).toInstance("Simple App");
- bind(InputStream.class).annotatedWith(Names.named("metaInfManifest")).toProvider(Providers.of(getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF")));
- }
- };
+ WebRequest request = super.newWebRequest(servletRequest, filterPath);
+ return request;
+ }
- return Modules.override(isisDefaults).with(overrides);
- }
+ @Override
+ protected Module newIsisWicketModule() {
+ final Module isisDefaults = super.newIsisWicketModule();
- private static String readLines(final Class> contextClass, final String resourceName) {
- try {
- List readLines = Resources.readLines(Resources.getResource(contextClass, resourceName), Charset.defaultCharset());
- final String aboutText = Joiner.on("\n").join(readLines);
- return aboutText;
- } catch (IOException e) {
- return "This is a simple app";
- }
+ final Module overrides = new AbstractModule() {
+ @Override
+ protected void configure() {
+ bind(String.class).annotatedWith(Names.named("applicationName")).toInstance("Simple App");
+ bind(String.class).annotatedWith(Names.named("applicationCss")).toInstance(
+ "css/application.css");
+ bind(String.class).annotatedWith(Names.named("applicationJs")).toInstance(
+ "scripts/application.js");
+ bind(String.class).annotatedWith(Names.named("welcomeMessage")).toInstance(
+ readLines(getClass(), "welcome.html"));
+ bind(String.class).annotatedWith(Names.named("aboutMessage")).toInstance("Simple App");
+ bind(InputStream.class).annotatedWith(Names.named("metaInfManifest")).toProvider(
+ Providers.of(getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF")));
+ }
+ };
+
+ return Modules.override(isisDefaults).with(overrides);
+ }
+
+ private static String readLines(final Class> contextClass, final String resourceName) {
+ try {
+ List readLines =
+ Resources.readLines(Resources.getResource(contextClass, resourceName),
+ Charset.defaultCharset());
+ final String aboutText = Joiner.on("\n").join(readLines);
+ return aboutText;
+ } catch (IOException e) {
+ return "This is a simple app";
}
+ }
}
diff --git a/null-object/src/main/java/com/iluwatar/nullobject/App.java b/null-object/src/main/java/com/iluwatar/nullobject/App.java
index 9cc4a14da..65f124c84 100644
--- a/null-object/src/main/java/com/iluwatar/nullobject/App.java
+++ b/null-object/src/main/java/com/iluwatar/nullobject/App.java
@@ -2,35 +2,27 @@ package com.iluwatar.nullobject;
/**
*
- * Null Object pattern replaces null values with neutral objects.
- * Many times this simplifies algorithms since no extra null checks
- * are needed.
+ * Null Object pattern replaces null values with neutral objects. Many times this simplifies
+ * algorithms since no extra null checks are needed.
*
- * In this example we build a binary tree where the nodes are either
- * normal or Null Objects. No null values are used in the tree making
- * the traversal easy.
+ * In this example we build a binary tree where the nodes are either normal or Null Objects. No null
+ * values are used in the tree making the traversal easy.
*
*/
-public class App
-{
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
-
- Node root = new NodeImpl("1",
- new NodeImpl("11",
- new NodeImpl("111",
- NullNode.getInstance(),
- NullNode.getInstance()),
- NullNode.getInstance()),
- new NodeImpl("12",
- NullNode.getInstance(),
- new NodeImpl("122",
- NullNode.getInstance(),
- NullNode.getInstance())));
+public class App {
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
- root.walk();
- }
+ Node root =
+ new NodeImpl("1", new NodeImpl("11", new NodeImpl("111", NullNode.getInstance(),
+ NullNode.getInstance()), NullNode.getInstance()), new NodeImpl("12",
+ NullNode.getInstance(), new NodeImpl("122", NullNode.getInstance(),
+ NullNode.getInstance())));
+
+ root.walk();
+ }
}
diff --git a/null-object/src/main/java/com/iluwatar/nullobject/Node.java b/null-object/src/main/java/com/iluwatar/nullobject/Node.java
index 3d52087c9..010c1b7f1 100644
--- a/null-object/src/main/java/com/iluwatar/nullobject/Node.java
+++ b/null-object/src/main/java/com/iluwatar/nullobject/Node.java
@@ -7,9 +7,13 @@ package com.iluwatar.nullobject;
*/
public interface Node {
- String getName();
- int getTreeSize();
- Node getLeft();
- Node getRight();
- void walk();
+ String getName();
+
+ int getTreeSize();
+
+ Node getLeft();
+
+ Node getRight();
+
+ void walk();
}
diff --git a/null-object/src/main/java/com/iluwatar/nullobject/NodeImpl.java b/null-object/src/main/java/com/iluwatar/nullobject/NodeImpl.java
index fc9c9c9e3..5de258890 100644
--- a/null-object/src/main/java/com/iluwatar/nullobject/NodeImpl.java
+++ b/null-object/src/main/java/com/iluwatar/nullobject/NodeImpl.java
@@ -7,44 +7,44 @@ package com.iluwatar.nullobject;
*/
public class NodeImpl implements Node {
- private final String name;
- private final Node left;
- private final Node right;
-
- public NodeImpl(String name, Node left, Node right) {
- this.name = name;
- this.left = left;
- this.right = right;
- }
-
- @Override
- public int getTreeSize() {
- return 1 + left.getTreeSize() + right.getTreeSize();
- }
+ private final String name;
+ private final Node left;
+ private final Node right;
- @Override
- public Node getLeft() {
- return left;
- }
+ public NodeImpl(String name, Node left, Node right) {
+ this.name = name;
+ this.left = left;
+ this.right = right;
+ }
- @Override
- public Node getRight() {
- return right;
- }
+ @Override
+ public int getTreeSize() {
+ return 1 + left.getTreeSize() + right.getTreeSize();
+ }
- @Override
- public String getName() {
- return name;
- }
+ @Override
+ public Node getLeft() {
+ return left;
+ }
- @Override
- public void walk() {
- System.out.println(name);
- if (left.getTreeSize() > 0) {
- left.walk();
- }
- if (right.getTreeSize() > 0) {
- right.walk();
- }
- }
+ @Override
+ public Node getRight() {
+ return right;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public void walk() {
+ System.out.println(name);
+ if (left.getTreeSize() > 0) {
+ left.walk();
+ }
+ if (right.getTreeSize() > 0) {
+ right.walk();
+ }
+ }
}
diff --git a/null-object/src/main/java/com/iluwatar/nullobject/NullNode.java b/null-object/src/main/java/com/iluwatar/nullobject/NullNode.java
index 4a0f4cd2b..992b34af3 100644
--- a/null-object/src/main/java/com/iluwatar/nullobject/NullNode.java
+++ b/null-object/src/main/java/com/iluwatar/nullobject/NullNode.java
@@ -9,36 +9,34 @@ package com.iluwatar.nullobject;
*/
public class NullNode implements Node {
- private static NullNode instance = new NullNode();
-
- private NullNode() {
- }
-
- public static NullNode getInstance() {
- return instance;
- }
-
- @Override
- public int getTreeSize() {
- return 0;
- }
+ private static NullNode instance = new NullNode();
- @Override
- public Node getLeft() {
- return null;
- }
+ private NullNode() {}
- @Override
- public Node getRight() {
- return null;
- }
+ public static NullNode getInstance() {
+ return instance;
+ }
- @Override
- public String getName() {
- return null;
- }
+ @Override
+ public int getTreeSize() {
+ return 0;
+ }
- @Override
- public void walk() {
- }
+ @Override
+ public Node getLeft() {
+ return null;
+ }
+
+ @Override
+ public Node getRight() {
+ return null;
+ }
+
+ @Override
+ public String getName() {
+ return null;
+ }
+
+ @Override
+ public void walk() {}
}
diff --git a/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java b/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java
index 7ddf2cabc..58f03da28 100644
--- a/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java
+++ b/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.nullobject.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/App.java b/object-pool/src/main/java/com/iluwatar/object/pool/App.java
index c1893a774..97670223d 100644
--- a/object-pool/src/main/java/com/iluwatar/object/pool/App.java
+++ b/object-pool/src/main/java/com/iluwatar/object/pool/App.java
@@ -2,48 +2,51 @@ package com.iluwatar.object.pool;
/**
*
- * When it is necessary to work with a large number of objects that are particularly expensive to instantiate
- * and each object is only needed for a short period of time, the performance of an entire application may be
- * adversely affected. An object pool design pattern may be deemed desirable in cases such as these.
+ * When it is necessary to work with a large number of objects that are particularly expensive to
+ * instantiate and each object is only needed for a short period of time, the performance of an
+ * entire application may be adversely affected. An object pool design pattern may be deemed
+ * desirable in cases such as these.
*
- * The object pool design pattern creates a set of objects that may be reused. When a new object is needed, it
- * is requested from the pool. If a previously prepared object is available it is returned immediately, avoiding
- * the instantiation cost. If no objects are present in the pool, a new item is created and returned. When the
- * object has been used and is no longer needed, it is returned to the pool, allowing it to be used again in the
- * future without repeating the computationally expensive instantiation process. It is important to note that
- * once an object has been used and returned, existing references will become invalid.
+ * The object pool design pattern creates a set of objects that may be reused. When a new object is
+ * needed, it is requested from the pool. If a previously prepared object is available it is
+ * returned immediately, avoiding the instantiation cost. If no objects are present in the pool, a
+ * new item is created and returned. When the object has been used and is no longer needed, it is
+ * returned to the pool, allowing it to be used again in the future without repeating the
+ * computationally expensive instantiation process. It is important to note that once an object has
+ * been used and returned, existing references will become invalid.
*
- * In this example we have created {@link OliphauntPool} inheriting from generic {@link ObjectPool}. {@link Oliphaunt}s can be checked
- * out from the pool and later returned to it. The pool tracks created instances and their status (available,
- * inUse).
+ * In this example we have created {@link OliphauntPool} inheriting from generic {@link ObjectPool}.
+ * {@link Oliphaunt}s can be checked out from the pool and later returned to it. The pool tracks
+ * created instances and their status (available, inUse).
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
- OliphauntPool pool = new OliphauntPool();
- System.out.println(pool);
- Oliphaunt oliphaunt1 = pool.checkOut();
- System.out.println("Checked out " + oliphaunt1);
- System.out.println(pool);
- Oliphaunt oliphaunt2 = pool.checkOut();
- System.out.println("Checked out " + oliphaunt2);
- Oliphaunt oliphaunt3 = pool.checkOut();
- System.out.println("Checked out " + oliphaunt3);
- System.out.println(pool);
- System.out.println("Checking in " + oliphaunt1);
- pool.checkIn(oliphaunt1);
- System.out.println("Checking in " + oliphaunt2);
- pool.checkIn(oliphaunt2);
- System.out.println(pool);
- Oliphaunt oliphaunt4 = pool.checkOut();
- System.out.println("Checked out " + oliphaunt4);
- Oliphaunt oliphaunt5 = pool.checkOut();
- System.out.println("Checked out " + oliphaunt5);
- System.out.println(pool);
- }
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ OliphauntPool pool = new OliphauntPool();
+ System.out.println(pool);
+ Oliphaunt oliphaunt1 = pool.checkOut();
+ System.out.println("Checked out " + oliphaunt1);
+ System.out.println(pool);
+ Oliphaunt oliphaunt2 = pool.checkOut();
+ System.out.println("Checked out " + oliphaunt2);
+ Oliphaunt oliphaunt3 = pool.checkOut();
+ System.out.println("Checked out " + oliphaunt3);
+ System.out.println(pool);
+ System.out.println("Checking in " + oliphaunt1);
+ pool.checkIn(oliphaunt1);
+ System.out.println("Checking in " + oliphaunt2);
+ pool.checkIn(oliphaunt2);
+ System.out.println(pool);
+ Oliphaunt oliphaunt4 = pool.checkOut();
+ System.out.println("Checked out " + oliphaunt4);
+ Oliphaunt oliphaunt5 = pool.checkOut();
+ System.out.println("Checked out " + oliphaunt5);
+ System.out.println(pool);
+ }
}
diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java b/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java
index 8b582630b..79d7d6345 100644
--- a/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java
+++ b/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java
@@ -10,28 +10,28 @@ import java.util.HashSet;
*/
public abstract class ObjectPool {
- private HashSet available = new HashSet<>();
- private HashSet inUse = new HashSet<>();
-
- protected abstract T create();
-
- public synchronized T checkOut() {
- if (available.size() <= 0) {
- available.add(create());
- }
- T instance = available.iterator().next();
- available.remove(instance);
- inUse.add(instance);
- return instance;
- }
-
- public synchronized void checkIn(T instance) {
- inUse.remove(instance);
- available.add(instance);
- }
-
- @Override
- public String toString() {
- return String.format("Pool available=%d inUse=%d", available.size(), inUse.size());
- }
+ private HashSet available = new HashSet<>();
+ private HashSet inUse = new HashSet<>();
+
+ protected abstract T create();
+
+ public synchronized T checkOut() {
+ if (available.size() <= 0) {
+ available.add(create());
+ }
+ T instance = available.iterator().next();
+ available.remove(instance);
+ inUse.add(instance);
+ return instance;
+ }
+
+ public synchronized void checkIn(T instance) {
+ inUse.remove(instance);
+ available.add(instance);
+ }
+
+ @Override
+ public String toString() {
+ return String.format("Pool available=%d inUse=%d", available.size(), inUse.size());
+ }
}
diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java b/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java
index 4b32e0ba1..aeefd6b3a 100644
--- a/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java
+++ b/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java
@@ -6,26 +6,26 @@ package com.iluwatar.object.pool;
*
*/
public class Oliphaunt {
-
- private static int counter = 1;
-
- private final int id;
-
- public Oliphaunt() {
- id = counter++;
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- public int getId() {
- return id;
- }
-
- @Override
- public String toString() {
- return String.format("Oliphaunt id=%d", id);
- }
+
+ private static int counter = 1;
+
+ private final int id;
+
+ public Oliphaunt() {
+ id = counter++;
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("Oliphaunt id=%d", id);
+ }
}
diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/OliphauntPool.java b/object-pool/src/main/java/com/iluwatar/object/pool/OliphauntPool.java
index a0cfc0d54..106f16c1b 100644
--- a/object-pool/src/main/java/com/iluwatar/object/pool/OliphauntPool.java
+++ b/object-pool/src/main/java/com/iluwatar/object/pool/OliphauntPool.java
@@ -7,8 +7,8 @@ package com.iluwatar.object.pool;
*/
public class OliphauntPool extends ObjectPool {
- @Override
- protected Oliphaunt create() {
- return new Oliphaunt();
- }
+ @Override
+ protected Oliphaunt create() {
+ return new Oliphaunt();
+ }
}
diff --git a/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java b/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java
index 4114590ec..fd2920d88 100644
--- a/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java
+++ b/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java
@@ -10,10 +10,10 @@ import com.iluwatar.object.pool.App;
*
*/
public class AppTest {
-
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java
index 91d30fddd..3f66dc808 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java
@@ -1,43 +1,45 @@
package com.iluwatar.poison.pill;
/**
- * One of the possible approaches to terminate Producer-Consumer pattern is using the Poison Pill idiom.
- * If you use Poison Pill as the termination signal then Producer is responsible to notify Consumer that
- * the exchange is over and reject any further messages. The Consumer receiving Poison Pill will stop
- * reading messages from the queue. You must also ensure that the Poison Pill will be the last message
- * that will be read from the queue (if you have prioritized queue then this can be tricky).
+ * One of the possible approaches to terminate Producer-Consumer pattern is using the Poison Pill
+ * idiom. If you use Poison Pill as the termination signal then Producer is responsible to notify
+ * Consumer that the exchange is over and reject any further messages. The Consumer receiving Poison
+ * Pill will stop reading messages from the queue. You must also ensure that the Poison Pill will be
+ * the last message that will be read from the queue (if you have prioritized queue then this can be
+ * tricky).
*
- * In simple cases the Poison Pill can be just a null-reference, but holding a unique separate shared
- * object-marker (with name "Poison" or "Poison Pill") is more clear and self describing.
+ * In simple cases the Poison Pill can be just a null-reference, but holding a unique separate
+ * shared object-marker (with name "Poison" or "Poison Pill") is more clear and self describing.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- MessageQueue queue = new SimpleMessageQueue(10000);
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ MessageQueue queue = new SimpleMessageQueue(10000);
- final Producer producer = new Producer("PRODUCER_1", queue);
- final Consumer consumer = new Consumer("CONSUMER_1", queue);
+ final Producer producer = new Producer("PRODUCER_1", queue);
+ final Consumer consumer = new Consumer("CONSUMER_1", queue);
- new Thread() {
- @Override
- public void run() {
- consumer.consume();
- }
- }.start();
+ new Thread() {
+ @Override
+ public void run() {
+ consumer.consume();
+ }
+ }.start();
- new Thread() {
- @Override
- public void run() {
- producer.send("hand shake");
- producer.send("some very important information");
- producer.send("bye!");
- producer.stop();
- }
- }.start();
- }
+ new Thread() {
+ @Override
+ public void run() {
+ producer.send("hand shake");
+ producer.send("some very important information");
+ producer.send("bye!");
+ producer.stop();
+ }
+ }.start();
+ }
}
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java
index 3bb9dcc56..ff06d7d5b 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java
@@ -7,32 +7,33 @@ import com.iluwatar.poison.pill.Message.Headers;
*/
public class Consumer {
- private final MQSubscribePoint queue;
- private final String name;
+ private final MQSubscribePoint queue;
+ private final String name;
- public Consumer(String name, MQSubscribePoint queue) {
- this.name = name;
- this.queue = queue;
- }
+ public Consumer(String name, MQSubscribePoint queue) {
+ this.name = name;
+ this.queue = queue;
+ }
- public void consume() {
- while (true) {
- Message msg;
- try {
- msg = queue.take();
- if (msg == Message.POISON_PILL) {
- System.out.println(String.format("Consumer %s receive request to terminate.", name));
- break;
- }
- } catch (InterruptedException e) {
- // allow thread to exit
- System.err.println(e);
- return;
- }
+ public void consume() {
+ while (true) {
+ Message msg;
+ try {
+ msg = queue.take();
+ if (msg == Message.POISON_PILL) {
+ System.out.println(String.format("Consumer %s receive request to terminate.", name));
+ break;
+ }
+ } catch (InterruptedException e) {
+ // allow thread to exit
+ System.err.println(e);
+ return;
+ }
- String sender = msg.getHeader(Headers.SENDER);
- String body = msg.getBody();
- System.out.println(String.format("Message [%s] from [%s] received by [%s]", body, sender, name));
- }
- }
+ String sender = msg.getHeader(Headers.SENDER);
+ String body = msg.getBody();
+ System.out.println(String.format("Message [%s] from [%s] received by [%s]", body, sender,
+ name));
+ }
+ }
}
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MQPublishPoint.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MQPublishPoint.java
index 9c72242be..a266d9f4d 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MQPublishPoint.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MQPublishPoint.java
@@ -5,5 +5,5 @@ package com.iluwatar.poison.pill;
*/
public interface MQPublishPoint {
- public void put(Message msg) throws InterruptedException;
+ public void put(Message msg) throws InterruptedException;
}
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MQSubscribePoint.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MQSubscribePoint.java
index f689835b6..c093b1412 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MQSubscribePoint.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MQSubscribePoint.java
@@ -5,5 +5,5 @@ package com.iluwatar.poison.pill;
*/
public interface MQSubscribePoint {
- public Message take() throws InterruptedException;
+ public Message take() throws InterruptedException;
}
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java
index 8e167790f..b0fc6d6dc 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java
@@ -3,51 +3,55 @@ package com.iluwatar.poison.pill;
import java.util.Map;
/**
- * Interface that implements the Message pattern and represents an inbound or outbound
- * message as part of an {@link Producer}-{@link Consumer} exchange.
+ * Interface that implements the Message pattern and represents an inbound or outbound message as
+ * part of an {@link Producer}-{@link Consumer} exchange.
*/
public interface Message {
- public static final Message POISON_PILL = new Message() {
+ public static final Message POISON_PILL = new Message() {
- @Override
- public void addHeader(Headers header, String value) {
- throw poison();
- }
+ @Override
+ public void addHeader(Headers header, String value) {
+ throw poison();
+ }
- @Override
- public String getHeader(Headers header) {
- throw poison();
- }
+ @Override
+ public String getHeader(Headers header) {
+ throw poison();
+ }
- @Override
- public Map getHeaders() {
- throw poison();
- }
+ @Override
+ public Map getHeaders() {
+ throw poison();
+ }
- @Override
- public void setBody(String body) {
- throw poison();
- }
+ @Override
+ public void setBody(String body) {
+ throw poison();
+ }
- @Override
- public String getBody() {
- throw poison();
- }
+ @Override
+ public String getBody() {
+ throw poison();
+ }
- private RuntimeException poison() {
- return new UnsupportedOperationException("Poison");
- }
+ private RuntimeException poison() {
+ return new UnsupportedOperationException("Poison");
+ }
- };
+ };
- public enum Headers {
- DATE, SENDER
- }
+ public enum Headers {
+ DATE, SENDER
+ }
- public void addHeader(Headers header, String value);
- public String getHeader(Headers header);
- public Map getHeaders();
- public void setBody(String body);
- public String getBody();
+ public void addHeader(Headers header, String value);
+
+ public String getHeader(Headers header);
+
+ public Map getHeaders();
+
+ public void setBody(String body);
+
+ public String getBody();
}
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java
index 56d086204..ecde39e35 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java
@@ -5,44 +5,46 @@ import java.util.Date;
import com.iluwatar.poison.pill.Message.Headers;
/**
- * Class responsible for producing unit of work that can be expressed as message and submitted to queue
+ * Class responsible for producing unit of work that can be expressed as message and submitted to
+ * queue
*/
public class Producer {
- private final MQPublishPoint queue;
- private final String name;
- private boolean isStopped;
+ private final MQPublishPoint queue;
+ private final String name;
+ private boolean isStopped;
- public Producer(String name, MQPublishPoint queue) {
- this.name = name;
- this.queue = queue;
- this.isStopped = false;
- }
+ public Producer(String name, MQPublishPoint queue) {
+ this.name = name;
+ this.queue = queue;
+ this.isStopped = false;
+ }
- public void send(String body) {
- if (isStopped) {
- throw new IllegalStateException(String.format("Producer %s was stopped and fail to deliver requested message [%s].", body, name));
- }
- Message msg = new SimpleMessage();
- msg.addHeader(Headers.DATE, new Date().toString());
- msg.addHeader(Headers.SENDER, name);
- msg.setBody(body);
+ public void send(String body) {
+ if (isStopped) {
+ throw new IllegalStateException(String.format(
+ "Producer %s was stopped and fail to deliver requested message [%s].", body, name));
+ }
+ Message msg = new SimpleMessage();
+ msg.addHeader(Headers.DATE, new Date().toString());
+ msg.addHeader(Headers.SENDER, name);
+ msg.setBody(body);
- try {
- queue.put(msg);
- } catch (InterruptedException e) {
- // allow thread to exit
- System.err.println(e);
- }
- }
+ try {
+ queue.put(msg);
+ } catch (InterruptedException e) {
+ // allow thread to exit
+ System.err.println(e);
+ }
+ }
- public void stop() {
- isStopped = true;
- try {
- queue.put(Message.POISON_PILL);
- } catch (InterruptedException e) {
- // allow thread to exit
- System.err.println(e);
- }
- }
+ public void stop() {
+ isStopped = true;
+ try {
+ queue.put(Message.POISON_PILL);
+ } catch (InterruptedException e) {
+ // allow thread to exit
+ System.err.println(e);
+ }
+ }
}
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java
index 61a8664f5..5b08d2295 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java
@@ -9,31 +9,31 @@ import java.util.Map;
*/
public class SimpleMessage implements Message {
- private Map headers = new HashMap<>();
- private String body;
+ private Map headers = new HashMap<>();
+ private String body;
- @Override
- public void addHeader(Headers header, String value) {
- headers.put(header, value);
- }
+ @Override
+ public void addHeader(Headers header, String value) {
+ headers.put(header, value);
+ }
- @Override
- public String getHeader(Headers header) {
- return headers.get(header);
- }
+ @Override
+ public String getHeader(Headers header) {
+ return headers.get(header);
+ }
- @Override
- public Map getHeaders() {
- return Collections.unmodifiableMap(headers);
- }
+ @Override
+ public Map getHeaders() {
+ return Collections.unmodifiableMap(headers);
+ }
- @Override
- public void setBody(String body) {
- this.body = body;
- }
+ @Override
+ public void setBody(String body) {
+ this.body = body;
+ }
- @Override
- public String getBody() {
- return body;
- }
+ @Override
+ public String getBody() {
+ return body;
+ }
}
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java
index 316ed33e5..dd0b3ed0a 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java
@@ -8,20 +8,19 @@ import java.util.concurrent.BlockingQueue;
*/
public class SimpleMessageQueue implements MessageQueue {
- private final BlockingQueue queue;
+ private final BlockingQueue queue;
- public SimpleMessageQueue(int bound) {
- queue = new ArrayBlockingQueue(bound);
- }
+ public SimpleMessageQueue(int bound) {
+ queue = new ArrayBlockingQueue(bound);
+ }
- @Override
- public void put(Message msg) throws InterruptedException {
- queue.put(msg);
- }
-
- @Override
- public Message take() throws InterruptedException {
- return queue.take();
- }
+ @Override
+ public void put(Message msg) throws InterruptedException {
+ queue.put(msg);
+ }
+ @Override
+ public Message take() throws InterruptedException {
+ return queue.take();
+ }
}
diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java
index 0730e5b10..c9b619016 100644
--- a/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java
+++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.poison.pill.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java
index a4e2ffa87..4c328043f 100644
--- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java
+++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java
@@ -2,37 +2,36 @@ package com.iluwatar.privateclassdata;
/**
*
- * The Private Class Data design pattern seeks to reduce exposure of attributes
- * by limiting their visibility. It reduces the number of class attributes by
- * encapsulating them in single data object. It allows the class designer to
- * remove write privilege of attributes that are intended to be set only during
- * construction, even from methods of the target class.
+ * The Private Class Data design pattern seeks to reduce exposure of attributes by limiting their
+ * visibility. It reduces the number of class attributes by encapsulating them in single data
+ * object. It allows the class designer to remove write privilege of attributes that are intended to
+ * be set only during construction, even from methods of the target class.
*
- * In the example we have normal {@link Stew} class with some ingredients given in
- * constructor. Then we have methods to enumerate the ingredients and to taste
- * the stew. The method for tasting the stew alters the private members of the
- * {@link Stew} class.
+ * In the example we have normal {@link Stew} class with some ingredients given in constructor. Then
+ * we have methods to enumerate the ingredients and to taste the stew. The method for tasting the
+ * stew alters the private members of the {@link Stew} class.
*
- * The problem is solved with the Private Class Data pattern. We introduce
- * {@link ImmutableStew} class that contains {@link StewData}. The private data members of
- * {@link Stew} are now in {@link StewData} and cannot be altered by {@link ImmutableStew} methods.
+ * The problem is solved with the Private Class Data pattern. We introduce {@link ImmutableStew}
+ * class that contains {@link StewData}. The private data members of {@link Stew} are now in
+ * {@link StewData} and cannot be altered by {@link ImmutableStew} methods.
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
- // stew is mutable
- Stew stew = new Stew(1, 2, 3, 4);
- stew.mix();
- stew.taste();
- stew.mix();
-
- // immutable stew protected with Private Class Data pattern
- ImmutableStew immutableStew = new ImmutableStew(2, 4, 3, 6);
- immutableStew.mix();
- }
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ // stew is mutable
+ Stew stew = new Stew(1, 2, 3, 4);
+ stew.mix();
+ stew.taste();
+ stew.mix();
+
+ // immutable stew protected with Private Class Data pattern
+ ImmutableStew immutableStew = new ImmutableStew(2, 4, 3, 6);
+ immutableStew.mix();
+ }
}
diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java
index ebaaf28a0..599a80407 100644
--- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java
+++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java
@@ -7,14 +7,15 @@ package com.iluwatar.privateclassdata;
*/
public class ImmutableStew {
- private StewData data;
-
- public ImmutableStew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
- data = new StewData(numPotatoes, numCarrots, numMeat, numPeppers);
- }
-
- public void mix() {
- System.out.println(String.format("Mixing the immutable stew we find: %d potatoes, %d carrots, %d meat and %d peppers",
- data.getNumPotatoes(), data.getNumCarrots(), data.getNumMeat(), data.getNumPeppers()));
- }
+ private StewData data;
+
+ public ImmutableStew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
+ data = new StewData(numPotatoes, numCarrots, numMeat, numPeppers);
+ }
+
+ public void mix() {
+ System.out.println(String.format(
+ "Mixing the immutable stew we find: %d potatoes, %d carrots, %d meat and %d peppers",
+ data.getNumPotatoes(), data.getNumCarrots(), data.getNumMeat(), data.getNumPeppers()));
+ }
}
diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java
index 6ad05044b..9deb32e16 100644
--- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java
+++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java
@@ -6,37 +6,38 @@ package com.iluwatar.privateclassdata;
*
*/
public class Stew {
-
- private int numPotatoes;
- private int numCarrots;
- private int numMeat;
- private int numPeppers;
-
- public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
- this.numPotatoes = numPotatoes;
- this.numCarrots = numCarrots;
- this.numMeat = numMeat;
- this.numPeppers = numPeppers;
- }
-
- public void mix() {
- System.out.println(String.format("Mixing the stew we find: %d potatoes, %d carrots, %d meat and %d peppers",
- numPotatoes, numCarrots, numMeat, numPeppers));
- }
-
- public void taste() {
- System.out.println("Tasting the stew");
- if (numPotatoes > 0) {
- numPotatoes--;
- }
- if (numCarrots > 0) {
- numCarrots--;
- }
- if (numMeat > 0) {
- numMeat--;
- }
- if (numPeppers > 0) {
- numPeppers--;
- }
- }
+
+ private int numPotatoes;
+ private int numCarrots;
+ private int numMeat;
+ private int numPeppers;
+
+ public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
+ this.numPotatoes = numPotatoes;
+ this.numCarrots = numCarrots;
+ this.numMeat = numMeat;
+ this.numPeppers = numPeppers;
+ }
+
+ public void mix() {
+ System.out.println(String.format(
+ "Mixing the stew we find: %d potatoes, %d carrots, %d meat and %d peppers", numPotatoes,
+ numCarrots, numMeat, numPeppers));
+ }
+
+ public void taste() {
+ System.out.println("Tasting the stew");
+ if (numPotatoes > 0) {
+ numPotatoes--;
+ }
+ if (numCarrots > 0) {
+ numCarrots--;
+ }
+ if (numMeat > 0) {
+ numMeat--;
+ }
+ if (numPeppers > 0) {
+ numPeppers--;
+ }
+ }
}
diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java
index f90d3bd18..23d54ccf4 100644
--- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java
+++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java
@@ -7,31 +7,31 @@ package com.iluwatar.privateclassdata;
*/
public class StewData {
- private int numPotatoes;
- private int numCarrots;
- private int numMeat;
- private int numPeppers;
-
- public StewData(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
- this.numPotatoes = numPotatoes;
- this.numCarrots = numCarrots;
- this.numMeat = numMeat;
- this.numPeppers = numPeppers;
- }
+ private int numPotatoes;
+ private int numCarrots;
+ private int numMeat;
+ private int numPeppers;
- public int getNumPotatoes() {
- return numPotatoes;
- }
+ public StewData(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
+ this.numPotatoes = numPotatoes;
+ this.numCarrots = numCarrots;
+ this.numMeat = numMeat;
+ this.numPeppers = numPeppers;
+ }
- public int getNumCarrots() {
- return numCarrots;
- }
+ public int getNumPotatoes() {
+ return numPotatoes;
+ }
- public int getNumMeat() {
- return numMeat;
- }
+ public int getNumCarrots() {
+ return numCarrots;
+ }
- public int getNumPeppers() {
- return numPeppers;
- }
+ public int getNumMeat() {
+ return numMeat;
+ }
+
+ public int getNumPeppers() {
+ return numPeppers;
+ }
}
diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java
index 92fc9b46a..6623a43ad 100644
--- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java
+++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.privateclassdata.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/property/src/main/java/com/iluwatar/property/App.java b/property/src/main/java/com/iluwatar/property/App.java
index ac46f5448..966bd36a5 100644
--- a/property/src/main/java/com/iluwatar/property/App.java
+++ b/property/src/main/java/com/iluwatar/property/App.java
@@ -6,53 +6,55 @@ import com.iluwatar.property.Character.Type;
*
* The Property pattern is also known as Prototype inheritance.
*
- * In prototype inheritance instead of classes, as opposite to Java class inheritance,
- * objects are used to create another objects and object hierarchies. Hierarchies are created using prototype chain
- * through delegation: every object has link to parent object. Any base (parent) object can be amended at runtime
- * (by adding or removal of some property), and all child objects will be affected as result.
+ * In prototype inheritance instead of classes, as opposite to Java class inheritance, objects are
+ * used to create another objects and object hierarchies. Hierarchies are created using prototype
+ * chain through delegation: every object has link to parent object. Any base (parent) object can be
+ * amended at runtime (by adding or removal of some property), and all child objects will be
+ * affected as result.
*
* In this example we demonstrate {@link Character} instantiation using the Property pattern.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- /* set up */
- Prototype charProto = new Character();
- charProto.set(Stats.STRENGTH, 10);
- charProto.set(Stats.AGILITY, 10);
- charProto.set(Stats.ARMOR, 10);
- charProto.set(Stats.ATTACK_POWER, 10);
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ /* set up */
+ Prototype charProto = new Character();
+ charProto.set(Stats.STRENGTH, 10);
+ charProto.set(Stats.AGILITY, 10);
+ charProto.set(Stats.ARMOR, 10);
+ charProto.set(Stats.ATTACK_POWER, 10);
- Character mageProto = new Character(Type.MAGE, charProto);
- mageProto.set(Stats.INTELLECT, 15);
- mageProto.set(Stats.SPIRIT, 10);
+ Character mageProto = new Character(Type.MAGE, charProto);
+ mageProto.set(Stats.INTELLECT, 15);
+ mageProto.set(Stats.SPIRIT, 10);
- Character warProto = new Character(Type.WARRIOR, charProto);
- warProto.set(Stats.RAGE, 15);
- warProto.set(Stats.ARMOR, 15); // boost default armor for warrior
+ Character warProto = new Character(Type.WARRIOR, charProto);
+ warProto.set(Stats.RAGE, 15);
+ warProto.set(Stats.ARMOR, 15); // boost default armor for warrior
- Character rogueProto = new Character(Type.ROGUE, charProto);
- rogueProto.set(Stats.ENERGY, 15);
- rogueProto.set(Stats.AGILITY, 15); // boost default agility for rogue
+ Character rogueProto = new Character(Type.ROGUE, charProto);
+ rogueProto.set(Stats.ENERGY, 15);
+ rogueProto.set(Stats.AGILITY, 15); // boost default agility for rogue
- /* usage */
- Character mag = new Character("Player_1", mageProto);
- mag.set(Stats.ARMOR, 8);
- System.out.println(mag);
+ /* usage */
+ Character mag = new Character("Player_1", mageProto);
+ mag.set(Stats.ARMOR, 8);
+ System.out.println(mag);
- Character warrior = new Character("Player_2", warProto);
- System.out.println(warrior);
+ Character warrior = new Character("Player_2", warProto);
+ System.out.println(warrior);
- Character rogue = new Character("Player_3", rogueProto);
- System.out.println(rogue);
+ Character rogue = new Character("Player_3", rogueProto);
+ System.out.println(rogue);
- Character rogueDouble = new Character("Player_4", rogue);
- rogueDouble.set(Stats.ATTACK_POWER, 12);
- System.out.println(rogueDouble);
- }
+ Character rogueDouble = new Character("Player_4", rogue);
+ rogueDouble.set(Stats.ATTACK_POWER, 12);
+ System.out.println(rogueDouble);
+ }
}
diff --git a/property/src/main/java/com/iluwatar/property/Character.java b/property/src/main/java/com/iluwatar/property/Character.java
index cb2fdf583..10b8f495d 100644
--- a/property/src/main/java/com/iluwatar/property/Character.java
+++ b/property/src/main/java/com/iluwatar/property/Character.java
@@ -8,110 +8,100 @@ import java.util.Map;
*/
public class Character implements Prototype {
- public enum Type {
- WARRIOR, MAGE, ROGUE
- }
+ public enum Type {
+ WARRIOR, MAGE, ROGUE
+ }
- private final Prototype prototype;
- private final Map properties = new HashMap<>();
+ private final Prototype prototype;
+ private final Map properties = new HashMap<>();
- private String name;
- private Type type;
+ private String name;
+ private Type type;
- public Character() {
- this.prototype = new Prototype() { // Null-value object
- @Override
- public Integer get(Stats stat) {
- return null;
- }
- @Override
- public boolean has(Stats stat) {
- return false;
- }
- @Override
- public void set(Stats stat, Integer val) {
- }
- @Override
- public void remove(Stats stat) {
- }}
- ;
- }
+ public Character() {
+ this.prototype = new Prototype() { // Null-value object
+ @Override
+ public Integer get(Stats stat) {
+ return null;
+ }
- public Character(Type type, Prototype prototype) {
- this.type = type;
- this.prototype = prototype;
- }
+ @Override
+ public boolean has(Stats stat) {
+ return false;
+ }
- public Character(String name, Character prototype) {
- this.name = name;
- this.type = prototype.type;
- this.prototype = prototype;
- }
+ @Override
+ public void set(Stats stat, Integer val) {}
- public String name() {
- return name;
- }
+ @Override
+ public void remove(Stats stat) {}
+ };
+ }
- public Type type() {
- return type;
- }
+ public Character(Type type, Prototype prototype) {
+ this.type = type;
+ this.prototype = prototype;
+ }
- @Override
- public Integer get(Stats stat) {
- boolean containsValue = properties.containsKey(stat);
- if (containsValue) {
- return properties.get(stat);
- } else {
- return prototype.get(stat);
- }
- }
+ public Character(String name, Character prototype) {
+ this.name = name;
+ this.type = prototype.type;
+ this.prototype = prototype;
+ }
- @Override
- public boolean has(Stats stat) {
- return get(stat) != null;
- }
+ public String name() {
+ return name;
+ }
- @Override
- public void set(Stats stat, Integer val) {
- properties.put(stat, val);
- }
+ public Type type() {
+ return type;
+ }
- @Override
- public void remove(Stats stat) {
- properties.put(stat, null);
- }
+ @Override
+ public Integer get(Stats stat) {
+ boolean containsValue = properties.containsKey(stat);
+ if (containsValue) {
+ return properties.get(stat);
+ } else {
+ return prototype.get(stat);
+ }
+ }
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- if (name != null) {
- builder
- .append("Player: ")
- .append(name)
- .append("\n");
- }
+ @Override
+ public boolean has(Stats stat) {
+ return get(stat) != null;
+ }
- if (type != null) {
- builder
- .append("Character type: ")
- .append(type.name())
- .append("\n");
- }
+ @Override
+ public void set(Stats stat, Integer val) {
+ properties.put(stat, val);
+ }
- builder.append("Stats:\n");
- for (Stats stat : Stats.values()) {
- Integer value = this.get(stat);
- if (value == null) {
- continue;
- }
- builder
- .append(" - ")
- .append(stat.name())
- .append(":")
- .append(value)
- .append("\n");
- }
- return builder.toString();
- }
+ @Override
+ public void remove(Stats stat) {
+ properties.put(stat, null);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ if (name != null) {
+ builder.append("Player: ").append(name).append("\n");
+ }
+
+ if (type != null) {
+ builder.append("Character type: ").append(type.name()).append("\n");
+ }
+
+ builder.append("Stats:\n");
+ for (Stats stat : Stats.values()) {
+ Integer value = this.get(stat);
+ if (value == null) {
+ continue;
+ }
+ builder.append(" - ").append(stat.name()).append(":").append(value).append("\n");
+ }
+ return builder.toString();
+ }
}
diff --git a/property/src/main/java/com/iluwatar/property/Prototype.java b/property/src/main/java/com/iluwatar/property/Prototype.java
index 12b4ce734..13b4c8608 100644
--- a/property/src/main/java/com/iluwatar/property/Prototype.java
+++ b/property/src/main/java/com/iluwatar/property/Prototype.java
@@ -5,8 +5,11 @@ package com.iluwatar.property;
*/
public interface Prototype {
- public Integer get(Stats stat);
- public boolean has(Stats stat);
- public void set(Stats stat, Integer val);
- public void remove(Stats stat);
+ public Integer get(Stats stat);
+
+ public boolean has(Stats stat);
+
+ public void set(Stats stat, Integer val);
+
+ public void remove(Stats stat);
}
diff --git a/property/src/main/java/com/iluwatar/property/Stats.java b/property/src/main/java/com/iluwatar/property/Stats.java
index b791a9dec..5ce71dcfe 100644
--- a/property/src/main/java/com/iluwatar/property/Stats.java
+++ b/property/src/main/java/com/iluwatar/property/Stats.java
@@ -5,5 +5,5 @@ package com.iluwatar.property;
*/
public enum Stats {
- AGILITY, STRENGTH, ATTACK_POWER, ARMOR, INTELLECT, SPIRIT, ENERGY, RAGE
+ AGILITY, STRENGTH, ATTACK_POWER, ARMOR, INTELLECT, SPIRIT, ENERGY, RAGE
}
diff --git a/property/src/test/java/com/iluwatar/property/AppTest.java b/property/src/test/java/com/iluwatar/property/AppTest.java
index 1e8078352..75be2f649 100644
--- a/property/src/test/java/com/iluwatar/property/AppTest.java
+++ b/property/src/test/java/com/iluwatar/property/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.property.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/App.java b/prototype/src/main/java/com/iluwatar/prototype/App.java
index 74bb6989d..77c727a39 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/App.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/App.java
@@ -2,44 +2,43 @@ package com.iluwatar.prototype;
/**
*
- * The Prototype pattern is a creational design pattern in software development. It is
- * used when the type of objects to create is determined by a prototypical instance,
- * which is cloned to produce new objects. This pattern is used to:
- * - avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
- * - avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword)
+ * The Prototype pattern is a creational design pattern in software development. It is used when the
+ * type of objects to create is determined by a prototypical instance, which is cloned to produce
+ * new objects. This pattern is used to: - avoid subclasses of an object creator in the client
+ * application, like the abstract factory pattern does. - avoid the inherent cost of creating a new
+ * object in the standard way (e.g., using the 'new' keyword)
*
- * In this example we have a factory class ({@link HeroFactoryImpl}) producing objects by
- * cloning the existing ones. The factory's prototype objects are given as constructor parameters.
+ * In this example we have a factory class ({@link HeroFactoryImpl}) producing objects by cloning
+ * the existing ones. The factory's prototype objects are given as constructor parameters.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- HeroFactory factory;
- Mage mage;
- Warlord warlord;
- Beast beast;
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ HeroFactory factory;
+ Mage mage;
+ Warlord warlord;
+ Beast beast;
- factory = new HeroFactoryImpl(new ElfMage(), new ElfWarlord(),
- new ElfBeast());
- mage = factory.createMage();
- warlord = factory.createWarlord();
- beast = factory.createBeast();
- System.out.println(mage);
- System.out.println(warlord);
- System.out.println(beast);
+ factory = new HeroFactoryImpl(new ElfMage(), new ElfWarlord(), new ElfBeast());
+ mage = factory.createMage();
+ warlord = factory.createWarlord();
+ beast = factory.createBeast();
+ System.out.println(mage);
+ System.out.println(warlord);
+ System.out.println(beast);
- factory = new HeroFactoryImpl(new OrcMage(), new OrcWarlord(),
- new OrcBeast());
- mage = factory.createMage();
- warlord = factory.createWarlord();
- beast = factory.createBeast();
- System.out.println(mage);
- System.out.println(warlord);
- System.out.println(beast);
- }
+ factory = new HeroFactoryImpl(new OrcMage(), new OrcWarlord(), new OrcBeast());
+ mage = factory.createMage();
+ warlord = factory.createWarlord();
+ beast = factory.createBeast();
+ System.out.println(mage);
+ System.out.println(warlord);
+ System.out.println(beast);
+ }
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/Beast.java b/prototype/src/main/java/com/iluwatar/prototype/Beast.java
index 028fa11b8..1b6d5d9a4 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/Beast.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/Beast.java
@@ -7,7 +7,7 @@ package com.iluwatar.prototype;
*/
public abstract class Beast extends Prototype {
- @Override
- public abstract Beast clone() throws CloneNotSupportedException;
+ @Override
+ public abstract Beast clone() throws CloneNotSupportedException;
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java
index b2b517207..f5cb8bdaf 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java
@@ -7,20 +7,18 @@ package com.iluwatar.prototype;
*/
public class ElfBeast extends Beast {
- public ElfBeast() {
- }
+ public ElfBeast() {}
- public ElfBeast(ElfBeast beast) {
- }
+ public ElfBeast(ElfBeast beast) {}
- @Override
- public Beast clone() throws CloneNotSupportedException {
- return new ElfBeast(this);
- }
+ @Override
+ public Beast clone() throws CloneNotSupportedException {
+ return new ElfBeast(this);
+ }
- @Override
- public String toString() {
- return "Elven eagle";
- }
+ @Override
+ public String toString() {
+ return "Elven eagle";
+ }
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java
index b502350c3..c801e4007 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java
@@ -7,20 +7,18 @@ package com.iluwatar.prototype;
*/
public class ElfMage extends Mage {
- public ElfMage() {
- }
+ public ElfMage() {}
- public ElfMage(ElfMage mage) {
- }
+ public ElfMage(ElfMage mage) {}
- @Override
- public Mage clone() throws CloneNotSupportedException {
- return new ElfMage(this);
- }
+ @Override
+ public Mage clone() throws CloneNotSupportedException {
+ return new ElfMage(this);
+ }
- @Override
- public String toString() {
- return "Elven mage";
- }
+ @Override
+ public String toString() {
+ return "Elven mage";
+ }
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java
index 7f5829797..8b5167b0e 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java
@@ -7,20 +7,18 @@ package com.iluwatar.prototype;
*/
public class ElfWarlord extends Warlord {
- public ElfWarlord() {
- }
+ public ElfWarlord() {}
- public ElfWarlord(ElfWarlord warlord) {
- }
+ public ElfWarlord(ElfWarlord warlord) {}
- @Override
- public Warlord clone() throws CloneNotSupportedException {
- return new ElfWarlord(this);
- }
+ @Override
+ public Warlord clone() throws CloneNotSupportedException {
+ return new ElfWarlord(this);
+ }
- @Override
- public String toString() {
- return "Elven warlord";
- }
+ @Override
+ public String toString() {
+ return "Elven warlord";
+ }
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java b/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java
index 468eefcb5..bf52b9787 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java
@@ -7,10 +7,10 @@ package com.iluwatar.prototype;
*/
public interface HeroFactory {
- Mage createMage();
+ Mage createMage();
- Warlord createWarlord();
+ Warlord createWarlord();
- Beast createBeast();
+ Beast createBeast();
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java
index dc440f41e..4c5a60bcd 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java
@@ -7,38 +7,38 @@ package com.iluwatar.prototype;
*/
public class HeroFactoryImpl implements HeroFactory {
- private Mage mage;
- private Warlord warlord;
- private Beast beast;
+ private Mage mage;
+ private Warlord warlord;
+ private Beast beast;
- public HeroFactoryImpl(Mage mage, Warlord warlord, Beast beast) {
- this.mage = mage;
- this.warlord = warlord;
- this.beast = beast;
- }
+ public HeroFactoryImpl(Mage mage, Warlord warlord, Beast beast) {
+ this.mage = mage;
+ this.warlord = warlord;
+ this.beast = beast;
+ }
- public Mage createMage() {
- try {
- return mage.clone();
- } catch (CloneNotSupportedException e) {
- return null;
- }
- }
+ public Mage createMage() {
+ try {
+ return mage.clone();
+ } catch (CloneNotSupportedException e) {
+ return null;
+ }
+ }
- public Warlord createWarlord() {
- try {
- return warlord.clone();
- } catch (CloneNotSupportedException e) {
- return null;
- }
- }
+ public Warlord createWarlord() {
+ try {
+ return warlord.clone();
+ } catch (CloneNotSupportedException e) {
+ return null;
+ }
+ }
- public Beast createBeast() {
- try {
- return beast.clone();
- } catch (CloneNotSupportedException e) {
- return null;
- }
- }
+ public Beast createBeast() {
+ try {
+ return beast.clone();
+ } catch (CloneNotSupportedException e) {
+ return null;
+ }
+ }
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/Mage.java b/prototype/src/main/java/com/iluwatar/prototype/Mage.java
index 7ba192487..73e4ee0a0 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/Mage.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/Mage.java
@@ -7,7 +7,7 @@ package com.iluwatar.prototype;
*/
public abstract class Mage extends Prototype {
- @Override
- public abstract Mage clone() throws CloneNotSupportedException;
+ @Override
+ public abstract Mage clone() throws CloneNotSupportedException;
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java
index 2af2fefa9..50a6b5ae2 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java
@@ -7,20 +7,18 @@ package com.iluwatar.prototype;
*/
public class OrcBeast extends Beast {
- public OrcBeast() {
- }
+ public OrcBeast() {}
- public OrcBeast(OrcBeast beast) {
- }
+ public OrcBeast(OrcBeast beast) {}
- @Override
- public Beast clone() throws CloneNotSupportedException {
- return new OrcBeast(this);
- }
+ @Override
+ public Beast clone() throws CloneNotSupportedException {
+ return new OrcBeast(this);
+ }
- @Override
- public String toString() {
- return "Orcish wolf";
- }
+ @Override
+ public String toString() {
+ return "Orcish wolf";
+ }
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java
index 1f52a25d9..f27d12519 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java
@@ -7,20 +7,18 @@ package com.iluwatar.prototype;
*/
public class OrcMage extends Mage {
- public OrcMage() {
- }
+ public OrcMage() {}
- public OrcMage(OrcMage mage) {
- }
+ public OrcMage(OrcMage mage) {}
- @Override
- public Mage clone() throws CloneNotSupportedException {
- return new OrcMage(this);
- }
+ @Override
+ public Mage clone() throws CloneNotSupportedException {
+ return new OrcMage(this);
+ }
- @Override
- public String toString() {
- return "Orcish mage";
- }
+ @Override
+ public String toString() {
+ return "Orcish mage";
+ }
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java
index 53814d1c2..d21816d8e 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java
@@ -7,20 +7,18 @@ package com.iluwatar.prototype;
*/
public class OrcWarlord extends Warlord {
- public OrcWarlord() {
- }
+ public OrcWarlord() {}
- public OrcWarlord(OrcWarlord warlord) {
- }
+ public OrcWarlord(OrcWarlord warlord) {}
- @Override
- public Warlord clone() throws CloneNotSupportedException {
- return new OrcWarlord(this);
- }
+ @Override
+ public Warlord clone() throws CloneNotSupportedException {
+ return new OrcWarlord(this);
+ }
- @Override
- public String toString() {
- return "Orcish warlord";
- }
+ @Override
+ public String toString() {
+ return "Orcish warlord";
+ }
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/Prototype.java b/prototype/src/main/java/com/iluwatar/prototype/Prototype.java
index eb2520c35..272eeaf37 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/Prototype.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/Prototype.java
@@ -7,7 +7,7 @@ package com.iluwatar.prototype;
*/
public abstract class Prototype implements Cloneable {
- @Override
- public abstract Object clone() throws CloneNotSupportedException;
+ @Override
+ public abstract Object clone() throws CloneNotSupportedException;
}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/Warlord.java b/prototype/src/main/java/com/iluwatar/prototype/Warlord.java
index bfd5c594a..f4a965ef3 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/Warlord.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/Warlord.java
@@ -7,7 +7,7 @@ package com.iluwatar.prototype;
*/
public abstract class Warlord extends Prototype {
- @Override
- public abstract Warlord clone() throws CloneNotSupportedException;
+ @Override
+ public abstract Warlord clone() throws CloneNotSupportedException;
}
diff --git a/prototype/src/test/java/com/iluwatar/prototype/AppTest.java b/prototype/src/test/java/com/iluwatar/prototype/AppTest.java
index 030f5472c..c2b8ea4ff 100644
--- a/prototype/src/test/java/com/iluwatar/prototype/AppTest.java
+++ b/prototype/src/test/java/com/iluwatar/prototype/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.prototype.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/proxy/src/main/java/com/iluwatar/proxy/App.java b/proxy/src/main/java/com/iluwatar/proxy/App.java
index 420ad5c0a..25a903e41 100644
--- a/proxy/src/main/java/com/iluwatar/proxy/App.java
+++ b/proxy/src/main/java/com/iluwatar/proxy/App.java
@@ -2,30 +2,30 @@ package com.iluwatar.proxy;
/**
*
- * A proxy, in its most general form, is a class functioning as an interface to something else.
- * The proxy could interface to anything: a network connection, a large object in memory, a file,
- * or some other resource that is expensive or impossible to duplicate. In short, a proxy is a
- * wrapper or agent object that is being called by the client to access the real serving object
- * behind the scenes.
+ * A proxy, in its most general form, is a class functioning as an interface to something else. The
+ * proxy could interface to anything: a network connection, a large object in memory, a file, or
+ * some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper
+ * or agent object that is being called by the client to access the real serving object behind the
+ * scenes.
*
- * The Proxy design pattern allows you to provide an interface to other objects by creating a
- * wrapper class as the proxy. The wrapper class, which is the proxy, can add additional
+ * The Proxy design pattern allows you to provide an interface to other objects by creating a
+ * wrapper class as the proxy. The wrapper class, which is the proxy, can add additional
* functionality to the object of interest without changing the object's code.
*
- * In this example the proxy ({@link WizardTowerProxy}) controls access to the actual object
- * ({@link WizardTower}).
+ * In this example the proxy ({@link WizardTowerProxy}) controls access to the actual object (
+ * {@link WizardTower}).
*
*/
public class App {
- public static void main(String[] args) {
+ public static void main(String[] args) {
- WizardTowerProxy tower = new WizardTowerProxy();
- tower.enter(new Wizard("Red wizard"));
- tower.enter(new Wizard("White wizard"));
- tower.enter(new Wizard("Black wizard"));
- tower.enter(new Wizard("Green wizard"));
- tower.enter(new Wizard("Brown wizard"));
+ WizardTowerProxy tower = new WizardTowerProxy();
+ tower.enter(new Wizard("Red wizard"));
+ tower.enter(new Wizard("White wizard"));
+ tower.enter(new Wizard("Black wizard"));
+ tower.enter(new Wizard("Green wizard"));
+ tower.enter(new Wizard("Brown wizard"));
- }
+ }
}
diff --git a/proxy/src/main/java/com/iluwatar/proxy/Wizard.java b/proxy/src/main/java/com/iluwatar/proxy/Wizard.java
index b6d5691f4..8351b45bf 100644
--- a/proxy/src/main/java/com/iluwatar/proxy/Wizard.java
+++ b/proxy/src/main/java/com/iluwatar/proxy/Wizard.java
@@ -7,15 +7,15 @@ package com.iluwatar.proxy;
*/
public class Wizard {
- private String name;
+ private String name;
- public Wizard(String name) {
- this.name = name;
- }
+ public Wizard(String name) {
+ this.name = name;
+ }
- @Override
- public String toString() {
- return name;
- }
+ @Override
+ public String toString() {
+ return name;
+ }
}
diff --git a/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java b/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java
index d4aa27c81..882312c21 100644
--- a/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java
+++ b/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java
@@ -7,8 +7,8 @@ package com.iluwatar.proxy;
*/
public class WizardTower {
- public void enter(Wizard wizard) {
- System.out.println(wizard + " enters the tower.");
- }
+ public void enter(Wizard wizard) {
+ System.out.println(wizard + " enters the tower.");
+ }
}
diff --git a/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java b/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java
index 567a998d1..42f37c768 100644
--- a/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java
+++ b/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java
@@ -7,17 +7,17 @@ package com.iluwatar.proxy;
*/
public class WizardTowerProxy extends WizardTower {
- private static final int NUM_WIZARDS_ALLOWED = 3;
+ private static final int NUM_WIZARDS_ALLOWED = 3;
- private int numWizards;
+ private int numWizards;
- @Override
- public void enter(Wizard wizard) {
- if (numWizards < NUM_WIZARDS_ALLOWED) {
- super.enter(wizard);
- numWizards++;
- } else {
- System.out.println(wizard + " is not allowed to enter!");
- }
- }
+ @Override
+ public void enter(Wizard wizard) {
+ if (numWizards < NUM_WIZARDS_ALLOWED) {
+ super.enter(wizard);
+ numWizards++;
+ } else {
+ System.out.println(wizard + " is not allowed to enter!");
+ }
+ }
}
diff --git a/proxy/src/test/java/com/iluwatar/proxy/AppTest.java b/proxy/src/test/java/com/iluwatar/proxy/AppTest.java
index 4d21b3d9a..a68629646 100644
--- a/proxy/src/test/java/com/iluwatar/proxy/AppTest.java
+++ b/proxy/src/test/java/com/iluwatar/proxy/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.proxy.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/App.java b/reactor/src/main/java/com/iluwatar/reactor/app/App.java
index 7bb01ddc8..2c49d9001 100644
--- a/reactor/src/main/java/com/iluwatar/reactor/app/App.java
+++ b/reactor/src/main/java/com/iluwatar/reactor/app/App.java
@@ -69,11 +69,13 @@ public class App {
private Dispatcher dispatcher;
/**
- * Creates an instance of App which will use provided dispatcher for dispatching events on reactor.
+ * Creates an instance of App which will use provided dispatcher for dispatching events on
+ * reactor.
+ *
* @param dispatcher the dispatcher that will be used to dispatch events.
*/
public App(Dispatcher dispatcher) {
- this.dispatcher = dispatcher;
+ this.dispatcher = dispatcher;
}
/**
@@ -106,7 +108,8 @@ public class App {
* Our application binds to multiple channels and uses same logging handler to handle incoming
* log requests.
*/
- reactor.registerChannel(tcpChannel(6666, loggingHandler)).registerChannel(tcpChannel(6667, loggingHandler))
+ reactor.registerChannel(tcpChannel(6666, loggingHandler))
+ .registerChannel(tcpChannel(6667, loggingHandler))
.registerChannel(udpChannel(6668, loggingHandler)).start();
}
@@ -120,7 +123,7 @@ public class App {
reactor.stop();
dispatcher.stop();
for (AbstractNioChannel channel : channels) {
- channel.getJavaChannel().close();
+ channel.getJavaChannel().close();
}
}
diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java b/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java
index 659f5da21..ee25b0be0 100644
--- a/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java
+++ b/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java
@@ -140,7 +140,8 @@ public class AppClient {
for (int i = 0; i < 4; i++) {
String message = clientName + " - Log request: " + i;
- DatagramPacket request = new DatagramPacket(message.getBytes(), message.getBytes().length, remoteAddress);
+ DatagramPacket request =
+ new DatagramPacket(message.getBytes(), message.getBytes().length, remoteAddress);
socket.send(request);
diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java b/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java
index 9f2f8a95c..df08426d0 100644
--- a/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java
+++ b/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java
@@ -24,7 +24,8 @@ public abstract class AbstractNioChannel {
private final SelectableChannel channel;
private final ChannelHandler handler;
- private final Map> channelToPendingWrites = new ConcurrentHashMap<>();
+ private final Map> channelToPendingWrites =
+ new ConcurrentHashMap<>();
private NioReactor reactor;
/**
diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java
index c5caaa7ff..f8be9b777 100644
--- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java
+++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java
@@ -71,7 +71,8 @@ public class NioServerSocketChannel extends AbstractNioChannel {
*/
@Override
public void bind() throws IOException {
- ((ServerSocketChannel) getJavaChannel()).socket().bind(new InetSocketAddress(InetAddress.getLocalHost(), port));
+ ((ServerSocketChannel) getJavaChannel()).socket().bind(
+ new InetSocketAddress(InetAddress.getLocalHost(), port));
((ServerSocketChannel) getJavaChannel()).configureBlocking(false);
System.out.println("Bound TCP socket at port: " + port);
}
diff --git a/reactor/src/test/java/com/iluwatar/reactor/app/AppTest.java b/reactor/src/test/java/com/iluwatar/reactor/app/AppTest.java
index 9abb4e690..10611bdc9 100644
--- a/reactor/src/test/java/com/iluwatar/reactor/app/AppTest.java
+++ b/reactor/src/test/java/com/iluwatar/reactor/app/AppTest.java
@@ -39,7 +39,7 @@ public class AppTest {
app.stop();
}
-
+
/**
* Test the application using same thread dispatcher.
*
diff --git a/repository/src/main/java/com/iluwatar/repository/App.java b/repository/src/main/java/com/iluwatar/repository/App.java
index 37a5f7962..fb9680cb6 100644
--- a/repository/src/main/java/com/iluwatar/repository/App.java
+++ b/repository/src/main/java/com/iluwatar/repository/App.java
@@ -7,61 +7,63 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* Repository pattern mediates between the domain and data mapping layers using a collection-like
- * interface for accessing domain objects. A system with complex domain model often benefits from
- * a layer that isolates domain objects from the details of the database access code and in such
+ * interface for accessing domain objects. A system with complex domain model often benefits from a
+ * layer that isolates domain objects from the details of the database access code and in such
* systems it can be worthwhile to build another layer of abstraction over the mapping layer where
- * query construction code is concentrated. This becomes more important when there are a large
+ * query construction code is concentrated. This becomes more important when there are a large
* number of domain classes or heavy querying. In these cases particularly, adding this layer helps
* minimize duplicate query logic.
*
- * In this example we utilize Spring Data to automatically generate a repository for us from the {@link Person}
- * domain object. Using the {@link PersonRepository} we perform CRUD operations on the entity. Underneath we have
- * configured in-memory H2 database for which schema is created and dropped on each run.
+ * In this example we utilize Spring Data to automatically generate a repository for us from the
+ * {@link Person} domain object. Using the {@link PersonRepository} we perform CRUD operations on
+ * the entity. Underneath we have configured in-memory H2 database for which schema is created and
+ * dropped on each run.
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
- "applicationContext.xml");
- PersonRepository repository = context.getBean(PersonRepository.class);
- Person peter = new Person("Peter", "Sagan");
- Person nasta = new Person("Nasta", "Kuzminova");
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ ClassPathXmlApplicationContext context =
+ new ClassPathXmlApplicationContext("applicationContext.xml");
+ PersonRepository repository = context.getBean(PersonRepository.class);
- // Add new Person records
- repository.save(peter);
- repository.save(nasta);
+ Person peter = new Person("Peter", "Sagan");
+ Person nasta = new Person("Nasta", "Kuzminova");
- // Count Person records
- System.out.println("Count Person records: " + repository.count());
+ // Add new Person records
+ repository.save(peter);
+ repository.save(nasta);
- // Print all records
- List persons = (List) repository.findAll();
- for (Person person : persons) {
- System.out.println(person);
- }
+ // Count Person records
+ System.out.println("Count Person records: " + repository.count());
- // Find Person by surname
- System.out.println("Find by surname 'Sagan': " + repository.findBySurname("Sagan"));
+ // Print all records
+ List persons = (List) repository.findAll();
+ for (Person person : persons) {
+ System.out.println(person);
+ }
- // Update Person
- nasta.setName("Barbora");
- nasta.setSurname("Spotakova");
- repository.save(nasta);
+ // Find Person by surname
+ System.out.println("Find by surname 'Sagan': " + repository.findBySurname("Sagan"));
- System.out.println("Find by id 2: " + repository.findOne(2L));
+ // Update Person
+ nasta.setName("Barbora");
+ nasta.setSurname("Spotakova");
+ repository.save(nasta);
- // Remove record from Person
- repository.delete(2L);
+ System.out.println("Find by id 2: " + repository.findOne(2L));
- // And finally count records
- System.out.println("Count Person records: " + repository.count());
+ // Remove record from Person
+ repository.delete(2L);
- context.close();
- }
+ // And finally count records
+ System.out.println("Count Person records: " + repository.count());
+
+ context.close();
+ }
}
diff --git a/repository/src/main/java/com/iluwatar/repository/Person.java b/repository/src/main/java/com/iluwatar/repository/Person.java
index 85d647b1a..97d5e7120 100644
--- a/repository/src/main/java/com/iluwatar/repository/Person.java
+++ b/repository/src/main/java/com/iluwatar/repository/Person.java
@@ -12,47 +12,45 @@ import javax.persistence.Id;
@Entity
public class Person {
- @Id
- @GeneratedValue
- private Long id;
- private String name;
- private String surname;
+ @Id
+ @GeneratedValue
+ private Long id;
+ private String name;
+ private String surname;
- public Person() {
- }
+ public Person() {}
- public Person(String name, String surname) {
- this.name = name;
- this.surname = surname;
- }
+ public Person(String name, String surname) {
+ this.name = name;
+ this.surname = surname;
+ }
- public Long getId() {
- return id;
- }
+ public Long getId() {
+ return id;
+ }
- public void setId(Long id) {
- this.id = id;
- }
+ public void setId(Long id) {
+ this.id = id;
+ }
- public String getName() {
- return name;
- }
+ public String getName() {
+ return name;
+ }
- public void setName(String name) {
- this.name = name;
- }
+ public void setName(String name) {
+ this.name = name;
+ }
- public String getSurname() {
- return surname;
- }
+ public String getSurname() {
+ return surname;
+ }
- public void setSurname(String surname) {
- this.surname = surname;
- }
+ public void setSurname(String surname) {
+ this.surname = surname;
+ }
- @Override
- public String toString() {
- return "Person [id=" + id + ", name=" + name + ", surname=" + surname
- + "]";
- }
+ @Override
+ public String toString() {
+ return "Person [id=" + id + ", name=" + name + ", surname=" + surname + "]";
+ }
}
diff --git a/repository/src/main/java/com/iluwatar/repository/PersonRepository.java b/repository/src/main/java/com/iluwatar/repository/PersonRepository.java
index fd20bc94c..167b40d19 100644
--- a/repository/src/main/java/com/iluwatar/repository/PersonRepository.java
+++ b/repository/src/main/java/com/iluwatar/repository/PersonRepository.java
@@ -12,6 +12,6 @@ import org.springframework.stereotype.Repository;
*/
@Repository
public interface PersonRepository extends CrudRepository {
-
- public List findBySurname(String surname);
+
+ public List findBySurname(String surname);
}
diff --git a/repository/src/test/java/com/iluwatar/repository/AppTest.java b/repository/src/test/java/com/iluwatar/repository/AppTest.java
index 14f597045..929f61941 100644
--- a/repository/src/test/java/com/iluwatar/repository/AppTest.java
+++ b/repository/src/test/java/com/iluwatar/repository/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.repository.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java
index 141aea4ec..32cd3792e 100644
--- a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java
+++ b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java
@@ -2,43 +2,40 @@ package com.iluwatar.resource.acquisition.is.initialization;
/**
*
- * Resource Acquisition Is Initialization pattern was developed
- * for exception safe resource management by C++ creator Bjarne
- * Stroustrup.
+ * Resource Acquisition Is Initialization pattern was developed for exception safe resource
+ * management by C++ creator Bjarne Stroustrup.
*
- * In RAII resource is tied to object lifetime: resource allocation
- * is done during object creation while resource deallocation is
- * done during object destruction.
+ * In RAII resource is tied to object lifetime: resource allocation is done during object creation
+ * while resource deallocation is done during object destruction.
*
- * In Java RAII is achieved with try-with-resources statement and
- * interfaces {@link Closeable} and {@link AutoCloseable}. The try-with-resources
- * statement ensures that each resource is closed at the end of the
- * statement. Any object that implements {@link java.lang.AutoCloseable}, which
- * includes all objects which implement {@link java.io.Closeable}, can be used
- * as a resource.
+ * In Java RAII is achieved with try-with-resources statement and interfaces {@link Closeable} and
+ * {@link AutoCloseable}. The try-with-resources statement ensures that each resource is closed at
+ * the end of the statement. Any object that implements {@link java.lang.AutoCloseable}, which
+ * includes all objects which implement {@link java.io.Closeable}, can be used as a resource.
*
- * In this example, {@link SlidingDoor} implements {@link AutoCloseable} and
- * {@link TreasureChest} implements {@link Closeable}. Running the example, we can
- * observe that both resources are automatically closed.
+ * In this example, {@link SlidingDoor} implements {@link AutoCloseable} and {@link TreasureChest}
+ * implements {@link Closeable}. Running the example, we can observe that both resources are
+ * automatically closed.
*
* http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- * @throws Exception
- */
- public static void main( String[] args ) throws Exception {
-
- try (SlidingDoor slidingDoor = new SlidingDoor()) {
- System.out.println("Walking in.");
- }
-
- try (TreasureChest treasureChest = new TreasureChest()) {
- System.out.println("Looting contents.");
- }
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ * @throws Exception
+ */
+ public static void main(String[] args) throws Exception {
+
+ try (SlidingDoor slidingDoor = new SlidingDoor()) {
+ System.out.println("Walking in.");
}
+
+ try (TreasureChest treasureChest = new TreasureChest()) {
+ System.out.println("Looting contents.");
+ }
+ }
}
diff --git a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java
index 2033707e6..985b761c2 100644
--- a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java
+++ b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java
@@ -7,12 +7,12 @@ package com.iluwatar.resource.acquisition.is.initialization;
*/
public class SlidingDoor implements AutoCloseable {
- public SlidingDoor() {
- System.out.println("Sliding door opens.");
- }
-
- @Override
- public void close() throws Exception {
- System.out.println("Sliding door closes.");
- }
+ public SlidingDoor() {
+ System.out.println("Sliding door opens.");
+ }
+
+ @Override
+ public void close() throws Exception {
+ System.out.println("Sliding door closes.");
+ }
}
diff --git a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java
index 4d6b1a863..525e69652 100644
--- a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java
+++ b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java
@@ -10,12 +10,12 @@ import java.io.IOException;
*/
public class TreasureChest implements Closeable {
- public TreasureChest() {
- System.out.println("Treasure chest opens.");
- }
-
- @Override
- public void close() throws IOException {
- System.out.println("Treasure chest closes.");
- }
+ public TreasureChest() {
+ System.out.println("Treasure chest opens.");
+ }
+
+ @Override
+ public void close() throws IOException {
+ System.out.println("Treasure chest closes.");
+ }
}
diff --git a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java
index e20815c3f..2859f74ba 100644
--- a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java
+++ b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.resource.acquisition.is.initialization.App;
*/
public class AppTest {
- @Test
- public void test() throws Exception {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() throws Exception {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/servant/src/main/java/com/iluwatar/servant/App.java b/servant/src/main/java/com/iluwatar/servant/App.java
index 832d3d52c..42babbc1d 100644
--- a/servant/src/main/java/com/iluwatar/servant/App.java
+++ b/servant/src/main/java/com/iluwatar/servant/App.java
@@ -4,55 +4,56 @@ import java.util.ArrayList;
/**
- * Servant offers some functionality to a group of classes without defining that functionality in each of them.
- * A Servant is a class whose instance provides methods that take care of a desired service,
- * while objects for which the servant does something, are taken as parameters.
+ * Servant offers some functionality to a group of classes without defining that functionality in
+ * each of them. A Servant is a class whose instance provides methods that take care of a desired
+ * service, while objects for which the servant does something, are taken as parameters.
*
* In this example {@link Servant} is serving {@link King} and {@link Queen}.
*
*/
public class App {
-
- static Servant jenkins = new Servant("Jenkins");
- static Servant travis = new Servant("Travis");
- /**
- * Program entry point
- * @param args
- */
- public static void main(String[] args) {
- scenario(jenkins, 1);
- scenario(travis, 0);
- }
+ static Servant jenkins = new Servant("Jenkins");
+ static Servant travis = new Servant("Travis");
- /*
- * Can add a List with enum Actions for variable scenarios
- * */
- public static void scenario(Servant servant, int compliment) {
- King k = new King();
- Queen q = new Queen();
+ /**
+ * Program entry point
+ *
+ * @param args
+ */
+ public static void main(String[] args) {
+ scenario(jenkins, 1);
+ scenario(travis, 0);
+ }
- ArrayList guests = new ArrayList<>();
- guests.add(k);
- guests.add(q);
+ /*
+ * Can add a List with enum Actions for variable scenarios
+ */
+ public static void scenario(Servant servant, int compliment) {
+ King k = new King();
+ Queen q = new Queen();
- //feed
- servant.feed(k);
- servant.feed(q);
- //serve drinks
- servant.giveWine(k);
- servant.giveWine(q);
- //compliment
- servant.GiveCompliments(guests.get(compliment));
+ ArrayList guests = new ArrayList<>();
+ guests.add(k);
+ guests.add(q);
- //outcome of the night
- for (Royalty r : guests)
- r.changeMood();
+ // feed
+ servant.feed(k);
+ servant.feed(q);
+ // serve drinks
+ servant.giveWine(k);
+ servant.giveWine(q);
+ // compliment
+ servant.GiveCompliments(guests.get(compliment));
- //check your luck
- if (servant.checkIfYouWillBeHanged(guests))
- System.out.println(servant.name + " will live another day");
- else
- System.out.println("Poor " + servant.name + ". His days are numbered");
- }
+ // outcome of the night
+ for (Royalty r : guests)
+ r.changeMood();
+
+ // check your luck
+ if (servant.checkIfYouWillBeHanged(guests))
+ System.out.println(servant.name + " will live another day");
+ else
+ System.out.println("Poor " + servant.name + ". His days are numbered");
+ }
}
diff --git a/servant/src/main/java/com/iluwatar/servant/King.java b/servant/src/main/java/com/iluwatar/servant/King.java
index 29ec88192..5e931c149 100644
--- a/servant/src/main/java/com/iluwatar/servant/King.java
+++ b/servant/src/main/java/com/iluwatar/servant/King.java
@@ -6,34 +6,36 @@ package com.iluwatar.servant;
*
*/
public class King implements Royalty {
-
- private boolean isDrunk;
- private boolean isHungry = true;
- private boolean isHappy;
- private boolean complimentReceived;
- @Override
- public void getFed() {
- isHungry = false;
- }
+ private boolean isDrunk;
+ private boolean isHungry = true;
+ private boolean isHappy;
+ private boolean complimentReceived;
- @Override
- public void getDrink() {
- isDrunk = true;
- }
+ @Override
+ public void getFed() {
+ isHungry = false;
+ }
- public void receiveCompliments() {
- complimentReceived = true;
- }
+ @Override
+ public void getDrink() {
+ isDrunk = true;
+ }
- @Override
- public void changeMood() {
- if (!isHungry && isDrunk) isHappy = true;
- if (complimentReceived) isHappy = false;
- }
+ public void receiveCompliments() {
+ complimentReceived = true;
+ }
- @Override
- public boolean getMood() {
- return isHappy;
- }
+ @Override
+ public void changeMood() {
+ if (!isHungry && isDrunk)
+ isHappy = true;
+ if (complimentReceived)
+ isHappy = false;
+ }
+
+ @Override
+ public boolean getMood() {
+ return isHappy;
+ }
}
diff --git a/servant/src/main/java/com/iluwatar/servant/Queen.java b/servant/src/main/java/com/iluwatar/servant/Queen.java
index 815106725..db5446d34 100644
--- a/servant/src/main/java/com/iluwatar/servant/Queen.java
+++ b/servant/src/main/java/com/iluwatar/servant/Queen.java
@@ -6,39 +6,40 @@ package com.iluwatar.servant;
*
*/
public class Queen implements Royalty {
-
- private boolean isDrunk = true;
- private boolean isHungry;
- private boolean isHappy;
- private boolean isFlirty = true;
- private boolean complimentReceived;
- @Override
- public void getFed() {
- isHungry = false;
- }
+ private boolean isDrunk = true;
+ private boolean isHungry;
+ private boolean isHappy;
+ private boolean isFlirty = true;
+ private boolean complimentReceived;
- @Override
- public void getDrink() {
- isDrunk = true;
- }
+ @Override
+ public void getFed() {
+ isHungry = false;
+ }
- public void receiveCompliments() {
- complimentReceived = true;
- }
+ @Override
+ public void getDrink() {
+ isDrunk = true;
+ }
- @Override
- public void changeMood() {
- if (complimentReceived && isFlirty && isDrunk) isHappy = true;
- }
+ public void receiveCompliments() {
+ complimentReceived = true;
+ }
- @Override
- public boolean getMood() {
- return isHappy;
- }
+ @Override
+ public void changeMood() {
+ if (complimentReceived && isFlirty && isDrunk)
+ isHappy = true;
+ }
- public void setFlirtiness(boolean f) {
- this.isFlirty = f;
- }
+ @Override
+ public boolean getMood() {
+ return isHappy;
+ }
+
+ public void setFlirtiness(boolean f) {
+ this.isFlirty = f;
+ }
}
diff --git a/servant/src/main/java/com/iluwatar/servant/Royalty.java b/servant/src/main/java/com/iluwatar/servant/Royalty.java
index 543ffd8d5..38a0a8e7d 100644
--- a/servant/src/main/java/com/iluwatar/servant/Royalty.java
+++ b/servant/src/main/java/com/iluwatar/servant/Royalty.java
@@ -7,13 +7,13 @@ package com.iluwatar.servant;
*/
interface Royalty {
- void getFed();
+ void getFed();
- void getDrink();
+ void getDrink();
- void changeMood();
+ void changeMood();
- void receiveCompliments();
+ void receiveCompliments();
- boolean getMood();
+ boolean getMood();
}
diff --git a/servant/src/main/java/com/iluwatar/servant/Servant.java b/servant/src/main/java/com/iluwatar/servant/Servant.java
index 8e61333d8..987bf8791 100644
--- a/servant/src/main/java/com/iluwatar/servant/Servant.java
+++ b/servant/src/main/java/com/iluwatar/servant/Servant.java
@@ -8,30 +8,31 @@ import java.util.ArrayList;
*
*/
public class Servant {
-
- public String name;
-
- public Servant(String name){
- this.name = name;
- }
- public void feed(Royalty r){
- r.getFed();
- }
-
- public void giveWine(Royalty r){
- r.getDrink();
- }
-
- public void GiveCompliments(Royalty r){
- r.receiveCompliments();
- }
-
- public boolean checkIfYouWillBeHanged(ArrayList tableGuests){
- boolean anotherDay = true;
- for( Royalty r : tableGuests )
- if( !r.getMood() ) anotherDay = false;
-
- return anotherDay;
- }
+ public String name;
+
+ public Servant(String name) {
+ this.name = name;
+ }
+
+ public void feed(Royalty r) {
+ r.getFed();
+ }
+
+ public void giveWine(Royalty r) {
+ r.getDrink();
+ }
+
+ public void GiveCompliments(Royalty r) {
+ r.receiveCompliments();
+ }
+
+ public boolean checkIfYouWillBeHanged(ArrayList tableGuests) {
+ boolean anotherDay = true;
+ for (Royalty r : tableGuests)
+ if (!r.getMood())
+ anotherDay = false;
+
+ return anotherDay;
+ }
}
diff --git a/servant/src/test/java/com/iluwatar/servant/AppTest.java b/servant/src/test/java/com/iluwatar/servant/AppTest.java
index 94a12b207..d5a404291 100644
--- a/servant/src/test/java/com/iluwatar/servant/AppTest.java
+++ b/servant/src/test/java/com/iluwatar/servant/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.servant.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java b/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java
index 47eb5231e..a7053165d 100644
--- a/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java
+++ b/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java
@@ -16,161 +16,163 @@ import com.iluwatar.servicelayer.wizard.WizardDaoImpl;
/**
- * Service layer defines an application's boundary with a layer of services that establishes
- * a set of available operations and coordinates the application's response in each operation.
+ * Service layer defines an application's boundary with a layer of services that establishes a set
+ * of available operations and coordinates the application's response in each operation.
*
- * Enterprise applications typically require different kinds of interfaces to the data
- * they store and the logic they implement: data loaders, user interfaces, integration gateways,
- * and others. Despite their different purposes, these interfaces often need common interactions
- * with the application to access and manipulate its data and invoke its business logic. The
- * interactions may be complex, involving transactions across multiple resources and the
- * coordination of several responses to an action. Encoding the logic of the interactions
- * separately in each interface causes a lot of duplication.
+ * Enterprise applications typically require different kinds of interfaces to the data they store
+ * and the logic they implement: data loaders, user interfaces, integration gateways, and others.
+ * Despite their different purposes, these interfaces often need common interactions with the
+ * application to access and manipulate its data and invoke its business logic. The interactions may
+ * be complex, involving transactions across multiple resources and the coordination of several
+ * responses to an action. Encoding the logic of the interactions separately in each interface
+ * causes a lot of duplication.
*
- * The example application demonstrates interactions between a client ({@link App}) and a service
- * ({@link MagicService}). The service is implemented with 3-layer architecture (entity, dao, service).
- * For persistence the example uses in-memory H2 database which is populated on each application
- * startup.
+ * The example application demonstrates interactions between a client ({@link App}) and a service (
+ * {@link MagicService}). The service is implemented with 3-layer architecture (entity, dao,
+ * service). For persistence the example uses in-memory H2 database which is populated on each
+ * application startup.
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
- // populate the in-memory database
- initData();
- // query the data using the service
- queryData();
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ // populate the in-memory database
+ initData();
+ // query the data using the service
+ queryData();
+ }
+
+ public static void initData() {
+ // spells
+ Spell spell1 = new Spell("Ice dart");
+ Spell spell2 = new Spell("Invisibility");
+ Spell spell3 = new Spell("Stun bolt");
+ Spell spell4 = new Spell("Confusion");
+ Spell spell5 = new Spell("Darkness");
+ Spell spell6 = new Spell("Fireball");
+ Spell spell7 = new Spell("Enchant weapon");
+ Spell spell8 = new Spell("Rock armour");
+ Spell spell9 = new Spell("Light");
+ Spell spell10 = new Spell("Bee swarm");
+ Spell spell11 = new Spell("Haste");
+ Spell spell12 = new Spell("Levitation");
+ Spell spell13 = new Spell("Magic lock");
+ Spell spell14 = new Spell("Summon hell bat");
+ Spell spell15 = new Spell("Water walking");
+ Spell spell16 = new Spell("Magic storm");
+ Spell spell17 = new Spell("Entangle");
+ SpellDao spellDao = new SpellDaoImpl();
+ spellDao.persist(spell1);
+ spellDao.persist(spell2);
+ spellDao.persist(spell3);
+ spellDao.persist(spell4);
+ spellDao.persist(spell5);
+ spellDao.persist(spell6);
+ spellDao.persist(spell7);
+ spellDao.persist(spell8);
+ spellDao.persist(spell9);
+ spellDao.persist(spell10);
+ spellDao.persist(spell11);
+ spellDao.persist(spell12);
+ spellDao.persist(spell13);
+ spellDao.persist(spell14);
+ spellDao.persist(spell15);
+ spellDao.persist(spell16);
+ spellDao.persist(spell17);
+
+ // spellbooks
+ SpellbookDao spellbookDao = new SpellbookDaoImpl();
+ Spellbook spellbook1 = new Spellbook("Book of Orgymon");
+ spellbookDao.persist(spellbook1);
+ spellbook1.addSpell(spell1);
+ spellbook1.addSpell(spell2);
+ spellbook1.addSpell(spell3);
+ spellbook1.addSpell(spell4);
+ spellbookDao.merge(spellbook1);
+ Spellbook spellbook2 = new Spellbook("Book of Aras");
+ spellbookDao.persist(spellbook2);
+ spellbook2.addSpell(spell5);
+ spellbook2.addSpell(spell6);
+ spellbookDao.merge(spellbook2);
+ Spellbook spellbook3 = new Spellbook("Book of Kritior");
+ spellbookDao.persist(spellbook3);
+ spellbook3.addSpell(spell7);
+ spellbook3.addSpell(spell8);
+ spellbook3.addSpell(spell9);
+ spellbookDao.merge(spellbook3);
+ Spellbook spellbook4 = new Spellbook("Book of Tamaex");
+ spellbookDao.persist(spellbook4);
+ spellbook4.addSpell(spell10);
+ spellbook4.addSpell(spell11);
+ spellbook4.addSpell(spell12);
+ spellbookDao.merge(spellbook4);
+ Spellbook spellbook5 = new Spellbook("Book of Idores");
+ spellbookDao.persist(spellbook5);
+ spellbook5.addSpell(spell13);
+ spellbookDao.merge(spellbook5);
+ Spellbook spellbook6 = new Spellbook("Book of Opaen");
+ spellbookDao.persist(spellbook6);
+ spellbook6.addSpell(spell14);
+ spellbook6.addSpell(spell15);
+ spellbookDao.merge(spellbook6);
+ Spellbook spellbook7 = new Spellbook("Book of Kihione");
+ spellbookDao.persist(spellbook7);
+ spellbook7.addSpell(spell16);
+ spellbook7.addSpell(spell17);
+ spellbookDao.merge(spellbook7);
+
+ // wizards
+ WizardDao wizardDao = new WizardDaoImpl();
+ Wizard wizard1 = new Wizard("Aderlard Boud");
+ wizardDao.persist(wizard1);
+ wizard1.addSpellbook(spellbookDao.findByName("Book of Orgymon"));
+ wizard1.addSpellbook(spellbookDao.findByName("Book of Aras"));
+ wizardDao.merge(wizard1);
+ Wizard wizard2 = new Wizard("Anaxis Bajraktari");
+ wizardDao.persist(wizard2);
+ wizard2.addSpellbook(spellbookDao.findByName("Book of Kritior"));
+ wizard2.addSpellbook(spellbookDao.findByName("Book of Tamaex"));
+ wizardDao.merge(wizard2);
+ Wizard wizard3 = new Wizard("Xuban Munoa");
+ wizardDao.persist(wizard3);
+ wizard3.addSpellbook(spellbookDao.findByName("Book of Idores"));
+ wizard3.addSpellbook(spellbookDao.findByName("Book of Opaen"));
+ wizardDao.merge(wizard3);
+ Wizard wizard4 = new Wizard("Blasius Dehooge");
+ wizardDao.persist(wizard4);
+ wizard4.addSpellbook(spellbookDao.findByName("Book of Kihione"));
+ wizardDao.merge(wizard4);
+ }
+
+ public static void queryData() {
+ MagicService service =
+ new MagicServiceImpl(new WizardDaoImpl(), new SpellbookDaoImpl(), new SpellDaoImpl());
+ System.out.println("Enumerating all wizards");
+ for (Wizard w : service.findAllWizards()) {
+ System.out.println(w.getName());
}
-
- public static void initData() {
- // spells
- Spell spell1 = new Spell("Ice dart");
- Spell spell2 = new Spell("Invisibility");
- Spell spell3 = new Spell("Stun bolt");
- Spell spell4 = new Spell("Confusion");
- Spell spell5 = new Spell("Darkness");
- Spell spell6 = new Spell("Fireball");
- Spell spell7 = new Spell("Enchant weapon");
- Spell spell8 = new Spell("Rock armour");
- Spell spell9 = new Spell("Light");
- Spell spell10 = new Spell("Bee swarm");
- Spell spell11 = new Spell("Haste");
- Spell spell12 = new Spell("Levitation");
- Spell spell13 = new Spell("Magic lock");
- Spell spell14 = new Spell("Summon hell bat");
- Spell spell15 = new Spell("Water walking");
- Spell spell16 = new Spell("Magic storm");
- Spell spell17 = new Spell("Entangle");
- SpellDao spellDao = new SpellDaoImpl();
- spellDao.persist(spell1);
- spellDao.persist(spell2);
- spellDao.persist(spell3);
- spellDao.persist(spell4);
- spellDao.persist(spell5);
- spellDao.persist(spell6);
- spellDao.persist(spell7);
- spellDao.persist(spell8);
- spellDao.persist(spell9);
- spellDao.persist(spell10);
- spellDao.persist(spell11);
- spellDao.persist(spell12);
- spellDao.persist(spell13);
- spellDao.persist(spell14);
- spellDao.persist(spell15);
- spellDao.persist(spell16);
- spellDao.persist(spell17);
-
- // spellbooks
- SpellbookDao spellbookDao = new SpellbookDaoImpl();
- Spellbook spellbook1 = new Spellbook("Book of Orgymon");
- spellbookDao.persist(spellbook1);
- spellbook1.addSpell(spell1);
- spellbook1.addSpell(spell2);
- spellbook1.addSpell(spell3);
- spellbook1.addSpell(spell4);
- spellbookDao.merge(spellbook1);
- Spellbook spellbook2 = new Spellbook("Book of Aras");
- spellbookDao.persist(spellbook2);
- spellbook2.addSpell(spell5);
- spellbook2.addSpell(spell6);
- spellbookDao.merge(spellbook2);
- Spellbook spellbook3 = new Spellbook("Book of Kritior");
- spellbookDao.persist(spellbook3);
- spellbook3.addSpell(spell7);
- spellbook3.addSpell(spell8);
- spellbook3.addSpell(spell9);
- spellbookDao.merge(spellbook3);
- Spellbook spellbook4 = new Spellbook("Book of Tamaex");
- spellbookDao.persist(spellbook4);
- spellbook4.addSpell(spell10);
- spellbook4.addSpell(spell11);
- spellbook4.addSpell(spell12);
- spellbookDao.merge(spellbook4);
- Spellbook spellbook5 = new Spellbook("Book of Idores");
- spellbookDao.persist(spellbook5);
- spellbook5.addSpell(spell13);
- spellbookDao.merge(spellbook5);
- Spellbook spellbook6 = new Spellbook("Book of Opaen");
- spellbookDao.persist(spellbook6);
- spellbook6.addSpell(spell14);
- spellbook6.addSpell(spell15);
- spellbookDao.merge(spellbook6);
- Spellbook spellbook7 = new Spellbook("Book of Kihione");
- spellbookDao.persist(spellbook7);
- spellbook7.addSpell(spell16);
- spellbook7.addSpell(spell17);
- spellbookDao.merge(spellbook7);
-
- // wizards
- WizardDao wizardDao = new WizardDaoImpl();
- Wizard wizard1 = new Wizard("Aderlard Boud");
- wizardDao.persist(wizard1);
- wizard1.addSpellbook(spellbookDao.findByName("Book of Orgymon"));
- wizard1.addSpellbook(spellbookDao.findByName("Book of Aras"));
- wizardDao.merge(wizard1);
- Wizard wizard2 = new Wizard("Anaxis Bajraktari");
- wizardDao.persist(wizard2);
- wizard2.addSpellbook(spellbookDao.findByName("Book of Kritior"));
- wizard2.addSpellbook(spellbookDao.findByName("Book of Tamaex"));
- wizardDao.merge(wizard2);
- Wizard wizard3 = new Wizard("Xuban Munoa");
- wizardDao.persist(wizard3);
- wizard3.addSpellbook(spellbookDao.findByName("Book of Idores"));
- wizard3.addSpellbook(spellbookDao.findByName("Book of Opaen"));
- wizardDao.merge(wizard3);
- Wizard wizard4 = new Wizard("Blasius Dehooge");
- wizardDao.persist(wizard4);
- wizard4.addSpellbook(spellbookDao.findByName("Book of Kihione"));
- wizardDao.merge(wizard4);
+ System.out.println("Enumerating all spellbooks");
+ for (Spellbook s : service.findAllSpellbooks()) {
+ System.out.println(s.getName());
}
-
- public static void queryData() {
- MagicService service = new MagicServiceImpl(new WizardDaoImpl(), new SpellbookDaoImpl(), new SpellDaoImpl());
- System.out.println("Enumerating all wizards");
- for (Wizard w: service.findAllWizards()) {
- System.out.println(w.getName());
- }
- System.out.println("Enumerating all spellbooks");
- for (Spellbook s: service.findAllSpellbooks()) {
- System.out.println(s.getName());
- }
- System.out.println("Enumerating all spells");
- for (Spell s: service.findAllSpells()) {
- System.out.println(s.getName());
- }
- System.out.println("Find wizards with spellbook 'Book of Idores'");
- List wizardsWithSpellbook = service.findWizardsWithSpellbook("Book of Idores");
- for (Wizard w: wizardsWithSpellbook) {
- System.out.println(String.format("%s has 'Book of Idores'", w.getName()));
- }
- System.out.println("Find wizards with spell 'Fireball'");
- List wizardsWithSpell = service.findWizardsWithSpell("Fireball");
- for (Wizard w: wizardsWithSpell) {
- System.out.println(String.format("%s has 'Fireball'", w.getName()));
- }
+ System.out.println("Enumerating all spells");
+ for (Spell s : service.findAllSpells()) {
+ System.out.println(s.getName());
}
+ System.out.println("Find wizards with spellbook 'Book of Idores'");
+ List wizardsWithSpellbook = service.findWizardsWithSpellbook("Book of Idores");
+ for (Wizard w : wizardsWithSpellbook) {
+ System.out.println(String.format("%s has 'Book of Idores'", w.getName()));
+ }
+ System.out.println("Find wizards with spell 'Fireball'");
+ List wizardsWithSpell = service.findWizardsWithSpell("Fireball");
+ for (Wizard w : wizardsWithSpell) {
+ System.out.println(String.format("%s has 'Fireball'", w.getName()));
+ }
+ }
}
diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/common/BaseEntity.java b/service-layer/src/main/java/com/iluwatar/servicelayer/common/BaseEntity.java
index ec0f8e197..d8c796427 100644
--- a/service-layer/src/main/java/com/iluwatar/servicelayer/common/BaseEntity.java
+++ b/service-layer/src/main/java/com/iluwatar/servicelayer/common/BaseEntity.java
@@ -11,9 +11,9 @@ import javax.persistence.Version;
*
*/
@MappedSuperclass
-@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
+@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class BaseEntity {
-
- @Version
- private Long version;
+
+ @Version
+ private Long version;
}
diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/common/Dao.java b/service-layer/src/main/java/com/iluwatar/servicelayer/common/Dao.java
index e1851b16f..73fa3b7af 100644
--- a/service-layer/src/main/java/com/iluwatar/servicelayer/common/Dao.java
+++ b/service-layer/src/main/java/com/iluwatar/servicelayer/common/Dao.java
@@ -11,13 +11,13 @@ import java.util.List;
*/
public interface Dao {
- E find(Long id);
-
- void persist(E entity);
-
- E merge(E entity);
-
- void delete(E entity);
-
- List findAll();
+ E find(Long id);
+
+ void persist(E entity);
+
+ E merge(E entity);
+
+ void delete(E entity);
+
+ List findAll();
}
diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java
index bc0116dac..eae9286fa 100644
--- a/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java
+++ b/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java
@@ -18,110 +18,105 @@ import com.iluwatar.servicelayer.hibernate.HibernateUtil;
*
*/
public abstract class DaoBaseImpl implements Dao {
-
- @SuppressWarnings("unchecked")
- protected Class persistentClass = (Class) ((ParameterizedType) getClass()
- .getGenericSuperclass()).getActualTypeArguments()[0];
- protected Session getSession() {
- return HibernateUtil.getSessionFactory().openSession();
- }
-
- @Override
- public E find(Long id) {
- Session session = getSession();
- Transaction tx = null;
- E result = null;
- try {
- tx = session.beginTransaction();
- Criteria criteria = session.createCriteria(persistentClass);
- criteria.add(Restrictions.idEq(id));
- result = (E) criteria.uniqueResult();
- tx.commit();
- }
- catch (Exception e) {
- if (tx!=null) tx.rollback();
- throw e;
- }
- finally {
- session.close();
- }
- return result;
- }
-
- @Override
- public void persist(E entity) {
- Session session = getSession();
- Transaction tx = null;
- try {
- tx = session.beginTransaction();
- session.persist(entity);
- tx.commit();
- }
- catch (Exception e) {
- if (tx!=null) tx.rollback();
- throw e;
- }
- finally {
- session.close();
- }
- }
-
- @Override
- public E merge(E entity) {
- Session session = getSession();
- Transaction tx = null;
- E result = null;
- try {
- tx = session.beginTransaction();
- result = (E) session.merge(entity);
- tx.commit();
- }
- catch (Exception e) {
- if (tx!=null) tx.rollback();
- throw e;
- }
- finally {
- session.close();
- }
- return result;
- }
-
- @Override
- public void delete(E entity) {
- Session session = getSession();
- Transaction tx = null;
- try {
- tx = session.beginTransaction();
- session.delete(entity);
- tx.commit();
- }
- catch (Exception e) {
- if (tx!=null) tx.rollback();
- throw e;
- }
- finally {
- session.close();
- }
- }
-
- @Override
- public List findAll() {
- Session session = getSession();
- Transaction tx = null;
- List result = null;
- try {
- tx = session.beginTransaction();
- Criteria criteria = session.createCriteria(persistentClass);
- result = criteria.list();
- }
- catch (Exception e) {
- if (tx!=null) tx.rollback();
- throw e;
- }
- finally {
- session.close();
- }
- return result;
- }
+ @SuppressWarnings("unchecked")
+ protected Class persistentClass = (Class) ((ParameterizedType) getClass()
+ .getGenericSuperclass()).getActualTypeArguments()[0];
+
+ protected Session getSession() {
+ return HibernateUtil.getSessionFactory().openSession();
+ }
+
+ @Override
+ public E find(Long id) {
+ Session session = getSession();
+ Transaction tx = null;
+ E result = null;
+ try {
+ tx = session.beginTransaction();
+ Criteria criteria = session.createCriteria(persistentClass);
+ criteria.add(Restrictions.idEq(id));
+ result = (E) criteria.uniqueResult();
+ tx.commit();
+ } catch (Exception e) {
+ if (tx != null)
+ tx.rollback();
+ throw e;
+ } finally {
+ session.close();
+ }
+ return result;
+ }
+
+ @Override
+ public void persist(E entity) {
+ Session session = getSession();
+ Transaction tx = null;
+ try {
+ tx = session.beginTransaction();
+ session.persist(entity);
+ tx.commit();
+ } catch (Exception e) {
+ if (tx != null)
+ tx.rollback();
+ throw e;
+ } finally {
+ session.close();
+ }
+ }
+
+ @Override
+ public E merge(E entity) {
+ Session session = getSession();
+ Transaction tx = null;
+ E result = null;
+ try {
+ tx = session.beginTransaction();
+ result = (E) session.merge(entity);
+ tx.commit();
+ } catch (Exception e) {
+ if (tx != null)
+ tx.rollback();
+ throw e;
+ } finally {
+ session.close();
+ }
+ return result;
+ }
+
+ @Override
+ public void delete(E entity) {
+ Session session = getSession();
+ Transaction tx = null;
+ try {
+ tx = session.beginTransaction();
+ session.delete(entity);
+ tx.commit();
+ } catch (Exception e) {
+ if (tx != null)
+ tx.rollback();
+ throw e;
+ } finally {
+ session.close();
+ }
+ }
+
+ @Override
+ public List findAll() {
+ Session session = getSession();
+ Transaction tx = null;
+ List result = null;
+ try {
+ tx = session.beginTransaction();
+ Criteria criteria = session.createCriteria(persistentClass);
+ result = criteria.list();
+ } catch (Exception e) {
+ if (tx != null)
+ tx.rollback();
+ throw e;
+ } finally {
+ session.close();
+ }
+ return result;
+ }
}
diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java b/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java
index 61d0f5d5d..9d1aec488 100644
--- a/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java
+++ b/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java
@@ -14,27 +14,25 @@ import com.iluwatar.servicelayer.wizard.Wizard;
*/
public class HibernateUtil {
- private static final SessionFactory sessionFactory;
+ private static final SessionFactory sessionFactory;
- static {
- try {
- sessionFactory = new Configuration()
- .addAnnotatedClass(Wizard.class)
- .addAnnotatedClass(Spellbook.class)
- .addAnnotatedClass(Spell.class)
- .setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
- .setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1")
- .setProperty("hibernate.current_session_context_class", "thread")
- .setProperty("hibernate.show_sql", "true")
- .setProperty("hibernate.hbm2ddl.auto", "create-drop")
- .buildSessionFactory();
- } catch (Throwable ex) {
- System.err.println("Initial SessionFactory creation failed." + ex);
- throw new ExceptionInInitializerError(ex);
- }
- }
+ static {
+ try {
+ sessionFactory =
+ new Configuration().addAnnotatedClass(Wizard.class).addAnnotatedClass(Spellbook.class)
+ .addAnnotatedClass(Spell.class)
+ .setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
+ .setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1")
+ .setProperty("hibernate.current_session_context_class", "thread")
+ .setProperty("hibernate.show_sql", "true")
+ .setProperty("hibernate.hbm2ddl.auto", "create-drop").buildSessionFactory();
+ } catch (Throwable ex) {
+ System.err.println("Initial SessionFactory creation failed." + ex);
+ throw new ExceptionInInitializerError(ex);
+ }
+ }
- public static SessionFactory getSessionFactory() {
- return sessionFactory;
- }
+ public static SessionFactory getSessionFactory() {
+ return sessionFactory;
+ }
}
diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicService.java b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicService.java
index 38742c78d..26f732aa8 100644
--- a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicService.java
+++ b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicService.java
@@ -14,13 +14,13 @@ import com.iluwatar.servicelayer.wizard.Wizard;
*/
public interface MagicService {
- List findAllWizards();
+ List findAllWizards();
- List findAllSpellbooks();
-
- List findAllSpells();
+ List findAllSpellbooks();
- List findWizardsWithSpellbook(String name);
+ List findAllSpells();
- List findWizardsWithSpell(String name);
+ List findWizardsWithSpellbook(String name);
+
+ List findWizardsWithSpell(String name);
}
diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java
index 37249894a..f46f55184 100644
--- a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java
+++ b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java
@@ -16,42 +16,42 @@ import com.iluwatar.servicelayer.wizard.WizardDao;
*
*/
public class MagicServiceImpl implements MagicService {
-
- private WizardDao wizardDao;
- private SpellbookDao spellbookDao;
- private SpellDao spellDao;
- public MagicServiceImpl(WizardDao wizardDao, SpellbookDao spellbookDao, SpellDao spellDao) {
- this.wizardDao = wizardDao;
- this.spellbookDao = spellbookDao;
- this.spellDao = spellDao;
- }
+ private WizardDao wizardDao;
+ private SpellbookDao spellbookDao;
+ private SpellDao spellDao;
- @Override
- public List findAllWizards() {
- return wizardDao.findAll();
- }
+ public MagicServiceImpl(WizardDao wizardDao, SpellbookDao spellbookDao, SpellDao spellDao) {
+ this.wizardDao = wizardDao;
+ this.spellbookDao = spellbookDao;
+ this.spellDao = spellDao;
+ }
- @Override
- public List findAllSpellbooks() {
- return spellbookDao.findAll();
- }
+ @Override
+ public List findAllWizards() {
+ return wizardDao.findAll();
+ }
- @Override
- public List findAllSpells() {
- return spellDao.findAll();
- }
+ @Override
+ public List findAllSpellbooks() {
+ return spellbookDao.findAll();
+ }
- @Override
- public List findWizardsWithSpellbook(String name) {
- Spellbook spellbook = spellbookDao.findByName(name);
- return new ArrayList(spellbook.getWizards());
- }
+ @Override
+ public List findAllSpells() {
+ return spellDao.findAll();
+ }
- @Override
- public List findWizardsWithSpell(String name) {
- Spell spell = spellDao.findByName(name);
- Spellbook spellbook = spell.getSpellbook();
- return new ArrayList(spellbook.getWizards());
- }
+ @Override
+ public List findWizardsWithSpellbook(String name) {
+ Spellbook spellbook = spellbookDao.findByName(name);
+ return new ArrayList(spellbook.getWizards());
+ }
+
+ @Override
+ public List findWizardsWithSpell(String name) {
+ Spell spell = spellDao.findByName(name);
+ Spellbook spellbook = spell.getSpellbook();
+ return new ArrayList