Reformat rest of the design patterns - Issue #224

This commit is contained in:
Ankur Kaushal 2015-11-01 21:29:13 -05:00
parent 449340bd2b
commit 306b1f3d31
337 changed files with 6744 additions and 6851 deletions

View File

@ -6,21 +6,21 @@ 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.
* <p>
* 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) {
@ -28,8 +28,7 @@ public class App {
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 3; i++) {
executorService.execute(() -> {
while (inventory.addItem(new Item()))
;
while (inventory.addItem(new Item()));
});
}

View File

@ -28,8 +28,7 @@ public class Inventory {
try {
if (items.size() < inventorySize) {
items.add(item);
System.out.println(Thread.currentThread()
+ ": items.size()=" + items.size()
System.out.println(Thread.currentThread() + ": items.size()=" + items.size()
+ ", inventorySize=" + inventorySize);
return true;
}
@ -39,5 +38,4 @@ public class Inventory {
}
return false;
}
}

View File

@ -6,20 +6,20 @@ 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.
* implementation of that method in the receiver. Sometimes the behaviour must also be determined by
* the type of the parameter.
* <p>
* 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.
* <p>
* 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).
* <p>
* 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.
*
*/
@ -27,6 +27,7 @@ public class App {
/**
* Program entry point
*
* @param args command line args
*/
public static void main(String[] args) {
@ -40,7 +41,10 @@ public class App {
System.out.println("");
// collision check
objects.stream().forEach(o1 -> objects.stream().forEach(o2 -> { if (o1 != o2 && o1.intersectsWith(o2)) o1.collision(o2); } ));
objects.stream().forEach(o1 -> objects.stream().forEach(o2 -> {
if (o1 != o2 && o1.intersectsWith(o2))
o1.collision(o2);
}));
System.out.println("");
// output eventual object statuses

View File

@ -2,8 +2,7 @@ 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 {

View File

@ -18,21 +18,25 @@ public class Meteoroid extends GameObject {
@Override
public void collisionResolve(FlamingAsteroid asteroid) {
System.out.println(String.format("%s hits %s.", asteroid.getClass().getSimpleName(), this.getClass().getSimpleName()));
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()));
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()));
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()));
System.out.println(String.format("%s hits %s.", iss.getClass().getSimpleName(), this.getClass()
.getSimpleName()));
}
}

View File

@ -2,8 +2,7 @@ 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 {
@ -23,18 +22,22 @@ public class Rectangle {
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());
return !(r.getLeft() > getRight() || r.getRight() < getLeft() || r.getTop() > getBottom() || r
.getBottom() < getTop());
}
@Override

View File

@ -18,34 +18,31 @@ public class SpaceStationMir extends GameObject {
@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()));
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()));
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()));
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()));
System.out.println(String.format("%s hits %s. %s is damaged!", iss.getClass().getSimpleName(),
this.getClass().getSimpleName(), this.getClass().getSimpleName()));
setDamaged(true);
}
}

View File

@ -5,22 +5,23 @@ 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.
* <p>
* 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.
* <p>
* 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) {

View File

@ -7,7 +7,8 @@ package com.iluwatar.event.aggregator;
*/
public enum Event {
STARK_SIGHTED("Stark sighted"), WARSHIPS_APPROACHING("Warships approaching"), TRAITOR_DETECTED("Traitor detected");
STARK_SIGHTED("Stark sighted"), WARSHIPS_APPROACHING("Warships approaching"), TRAITOR_DETECTED(
"Traitor detected");
private String description;

View File

@ -2,8 +2,7 @@ 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 {

View File

@ -7,7 +7,8 @@ package com.iluwatar.event.aggregator;
*/
public enum Weekday {
MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY("Saturday"), SUNDAY("Sunday");
MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY(
"Friday"), SATURDAY("Saturday"), SUNDAY("Sunday");
private String description;

View File

@ -1,4 +1,5 @@
package com.iluwatar.event.aggregator;
import org.junit.Test;
import com.iluwatar.event.aggregator.App;

View File

@ -4,19 +4,20 @@ 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.
* <p>
* 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
*/

View File

@ -5,9 +5,8 @@ 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 {

View File

@ -2,21 +2,22 @@ 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.
* <p>
* 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) {

View File

@ -16,5 +16,4 @@ public class DwarvenCartOperator extends DwarvenMineWorker {
public String name() {
return "Dwarf cart operator";
}
}

View File

@ -16,5 +16,4 @@ public class DwarvenGoldDigger extends DwarvenMineWorker {
public String name() {
return "Dwarf gold digger";
}
}

View File

@ -6,12 +6,10 @@ 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 {
@ -37,7 +35,8 @@ public class DwarvenGoldmineFacade {
makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP);
}
private void makeActions(Collection<DwarvenMineWorker> workers, DwarvenMineWorker.Action... actions) {
private void makeActions(Collection<DwarvenMineWorker> workers,
DwarvenMineWorker.Action... actions) {
for (DwarvenMineWorker worker : workers) {
worker.action(actions);
}

View File

@ -16,5 +16,4 @@ public class DwarvenTunnelDigger extends DwarvenMineWorker {
public String name() {
return "Dwarven tunnel digger";
}
}

View File

@ -2,23 +2,23 @@ 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 classesrather 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 classesrather than by calling a constructor.
* <p>
* 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) {

View File

@ -17,5 +17,4 @@ public class ElfWeapon implements Weapon {
public String toString() {
return "Elven " + weaponType;
}
}

View File

@ -10,5 +10,4 @@ public class OrcBlacksmith implements Blacksmith {
public Weapon manufactureWeapon(WeaponType weaponType) {
return new OrcWeapon(weaponType);
}
}

View File

@ -17,5 +17,4 @@ public class OrcWeapon implements Weapon {
public String toString() {
return "Orcish " + weaponType;
}
}

View File

@ -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.
* <p>
* 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,10 +27,8 @@ public class App {
public static void main(String[] args) {
List<Integer> 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);

View File

@ -7,7 +7,8 @@ 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.");
PRODUCTS("Products - This page lists the company's products."), COMPANY(
"Company - This page displays information about the company.");
private String title;

View File

@ -11,13 +11,14 @@ 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.
* 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.
* <p>
* 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.
* <p>
* http://facebook.github.io/flux/docs/overview.html
*
@ -26,6 +27,7 @@ public class App {
/**
* Program entry point
*
* @param args command line args
*/
public static void main(String[] args) {

View File

@ -21,8 +21,7 @@ public class Dispatcher {
private List<Store> stores = new LinkedList<>();
private Dispatcher() {
}
private Dispatcher() {}
public static Dispatcher getInstance() {
return instance;

View File

@ -5,8 +5,7 @@ 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 {

View File

@ -2,22 +2,23 @@ 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.
* <p>
* 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.
* <p>
* 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) {

View File

@ -9,8 +9,6 @@ public class HealingPotion implements Potion {
@Override
public void drink() {
System.out.println("You feel healed. (Potion="
+ System.identityHashCode(this) + ")");
System.out.println("You feel healed. (Potion=" + System.identityHashCode(this) + ")");
}
}

View File

@ -9,8 +9,6 @@ public class HolyWaterPotion implements Potion {
@Override
public void drink() {
System.out.println("You feel blessed. (Potion="
+ System.identityHashCode(this) + ")");
System.out.println("You feel blessed. (Potion=" + System.identityHashCode(this) + ")");
}
}

View File

@ -9,8 +9,6 @@ public class InvisibilityPotion implements Potion {
@Override
public void drink() {
System.out.println("You become invisible. (Potion="
+ System.identityHashCode(this) + ")");
System.out.println("You become invisible. (Potion=" + System.identityHashCode(this) + ")");
}
}

View File

@ -9,8 +9,6 @@ public class PoisonPotion implements Potion {
@Override
public void drink() {
System.out.println("Urgh! This is poisonous. (Potion="
+ System.identityHashCode(this) + ")");
System.out.println("Urgh! This is poisonous. (Potion=" + System.identityHashCode(this) + ")");
}
}

View File

@ -5,10 +5,9 @@ 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 {

View File

@ -9,7 +9,6 @@ public class StrengthPotion implements Potion {
@Override
public void drink() {
System.out.println("You feel strong. (Potion="
+ System.identityHashCode(this) + ")");
System.out.println("You feel strong. (Potion=" + System.identityHashCode(this) + ")");
}
}

View File

@ -8,63 +8,62 @@ import java.util.concurrent.LinkedBlockingQueue;
* {@link AsyncTask} and {@link AsynchronousService}.
*
* <p>
* <i>PROBLEM</i>
* <br/>
* 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
* <i>PROBLEM</i> <br/>
* 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.
*
* <p><i>INTENT</i>
* <br/>
* 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.
* <p>
* <i>INTENT</i> <br/>
* 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.
*
* <p>
* <i>APPLICABILITY</i>
* <br/>
* <i>APPLICABILITY</i> <br/>
* <ul>
* <li>UNIX network subsystems - In operating systems network operations are carried out
* asynchronously with help of hardware level interrupts.</li>
* <li>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.</li>
* <li>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.</i>
* <li>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.</li>
* <li>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.</i>
* </ul>
*
* <p>
* <i>IMPLEMENTATION</i>
* <br/>
* 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.
* <i>IMPLEMENTATION</i> <br/>
* 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.
* 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
/*
* New task received, lets pass that to async layer for computation. So both requests will be
* executed in parallel.
*/
service.execute(new ArithmeticSumTask(500));
@ -85,8 +84,8 @@ public class App {
}
/*
* 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.
* 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 {
@ -94,11 +93,10 @@ public class App {
}
/*
* 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.
* 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() {

View File

@ -3,41 +3,41 @@ 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 <O> type of result
*/
public interface AsyncTask<O> extends Callable<O> {
/**
* 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.
* 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.
* 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.
* 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.
* This is where the computation of task should reside. This method is called in context of
* background thread.
*/
@Override
O call() throws Exception;

View File

@ -9,25 +9,25 @@ 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.
* 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.
* asynchronous layer and synchronous layer. Different types of queues such as Priority queue, can
* be used to control the pattern of communication between the layers.
*/
public AsynchronousService(BlockingQueue<Runnable> workQueue) {
service = new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, workQueue);
@ -38,8 +38,8 @@ public class AsynchronousService {
* A non-blocking method which performs the task provided in background and returns immediately.
* <p>
* On successful completion of task the result is posted back using callback method
* {@link AsyncTask#onPostCall(Object)}, if task execution is unable to complete normally
* due to some exception then the reason for error is posted back using callback method
* {@link AsyncTask#onPostCall(Object)}, if task execution is unable to complete normally due to
* some exception then the reason for error is posted back using callback method
* {@link AsyncTask#onError(Throwable)}.
* <p>
* NOTE: The results are posted back in the context of background thread in this implementation.
@ -57,11 +57,11 @@ public class AsynchronousService {
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.
/*
* 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) {

View File

@ -1,16 +1,14 @@
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() {
}
public AbstractFilter() {}
public AbstractFilter(Filter next) {
this.next = next;

View File

@ -1,8 +1,9 @@
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
*
*/

View File

@ -2,32 +2,27 @@ 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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}
* <p>
*
* @author joshzambales
*
*/
@ -35,6 +30,7 @@ public class App{
/**
* Program entry point
*
* @param args command line args
*/
public static void main(String[] args) {

View File

@ -15,9 +15,11 @@ 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
*
@ -85,8 +87,8 @@ public class Client extends JFrame {
processButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Order order = new Order(jtFields[0].getText(), jtFields[1]
.getText(), jtAreas[0].getText(),
Order order =
new Order(jtFields[0].getText(), jtFields[1].getText(), jtAreas[0].getText(),
jtFields[2].getText(), jtAreas[1].getText());
jl.setText(sendRequest(order));
}

View File

@ -1,9 +1,10 @@
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
*
*/
@ -12,8 +13,7 @@ public class ContactFilter extends AbstractFilter {
@Override
public String execute(Order order) {
String result = super.execute(order);
if (order.getContactNumber() == null
|| order.getContactNumber().isEmpty()
if (order.getContactNumber() == null || order.getContactNumber().isEmpty()
|| order.getContactNumber().matches(".*[^\\d]+.*")
|| order.getContactNumber().length() != 11) {
return result + "Invalid contact number! ";

View File

@ -1,8 +1,8 @@
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
*
*/

View File

@ -1,9 +1,8 @@
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
*
@ -12,6 +11,7 @@ public interface Filter {
/**
* Execute order processing filter.
*
* @param order
* @return empty string on success, otherwise error message.
*/
@ -19,18 +19,21 @@ public interface Filter {
/**
* 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();

View File

@ -1,8 +1,8 @@
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
*
@ -12,7 +12,8 @@ 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]+.*")) {
if (order.getName() == null || order.getName().isEmpty()
|| order.getName().matches(".*[^\\w|\\s]+.*")) {
return result + "Invalid order! ";
} else {
return result;

View File

@ -12,8 +12,7 @@ public class Order {
private String depositNumber;
private String order;
public Order() {
}
public Order() {}
public Order(String name, String contactNumber, String address, String depositNumber, String order) {
this.name = name;

View File

@ -33,8 +33,9 @@ public class Target extends JFrame {
super("Order System");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(640, 480);
dtm = new DefaultTableModel(new Object[] { "Name", "Contact Number",
"Address", "Deposit Number", "Order" }, 0);
dtm =
new DefaultTableModel(new Object[] {"Name", "Contact Number", "Address", "Deposit Number",
"Order"}, 0);
jt = new JTable(dtm);
del = new JButton("Delete");
setup();
@ -59,8 +60,7 @@ public class Target extends JFrame {
}
public void execute(String[] request) {
dtm.addRow(new Object[] { request[0], request[1], request[2],
request[3], request[4] });
dtm.addRow(new Object[] {request[0], request[1], request[2], request[3], request[4]});
}
class DListener implements ActionListener {

View File

@ -4,14 +4,13 @@ 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.
* <p>
* 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 {
@ -20,8 +19,8 @@ public class App {
*
* Program entry point.
* <p>
* Expressions can be evaluated using prefix, infix or postfix notations
* This sample uses postfix, where operator comes after the operands
* 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
*
@ -35,36 +34,28 @@ public class App {
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("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()));
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("push to stack: %d", i.interpret()));
}
}
System.out
.println(String.format("result: %d", stack.pop().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 Expression getOperatorInstance(String s, Expression left,
Expression right) {
public static Expression getOperatorInstance(String s, Expression left, Expression right) {
switch (s) {
case "+":
return new PlusExpression(left, right);

View File

@ -10,8 +10,7 @@ public class MultiplyExpression extends Expression {
private Expression leftExpression;
private Expression rightExpression;
public MultiplyExpression(Expression leftExpression,
Expression rightExpression) {
public MultiplyExpression(Expression leftExpression, Expression rightExpression) {
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
}

View File

@ -26,5 +26,4 @@ public class NumberExpression extends Expression {
public String toString() {
return "number";
}
}

View File

@ -24,5 +24,4 @@ public class PlusExpression extends Expression {
public String toString() {
return "+";
}
}

View File

@ -2,19 +2,19 @@ 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.
* <p>
* 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) {

View File

@ -44,8 +44,7 @@ public class TreasureChestItemIterator implements ItemIterator {
tempIdx = -1;
break;
}
if (type.equals(ItemType.ANY)
|| items.get(tempIdx).getType().equals(type)) {
if (type.equals(ItemType.ANY) || items.get(tempIdx).getType().equals(type)) {
break;
}
}

View File

@ -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.
* <p>
* 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.
* <p>
* The data access layer is formed of Spring Data repositories <code>CakeDao</code>, <code>CakeToppingDao</code> and
* <code>CakeLayerDao</code>. 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 <code>CakeDao</code>,
* <code>CakeToppingDao</code> and <code>CakeLayerDao</code>. The repositories can be used for CRUD
* operations on cakes, cake toppings and cake layers respectively.
* <p>
* The business layer is built on top of the data access layer. <code>CakeBakingService</code> 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. <code>CakeBakingService</code>
* 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.
* <p>
* 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.
* <p>
* 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 (<code>CakeInfo</code>, <code>CakeToppingInfo</code>, <code>CakeLayerInfo</code>)
* to translate data between layers. In other words, <code>CakeBakingService</code> cannot
* return entities (<code>Cake</code>, <code>CakeTopping</code>, <code>CakeLayer</code>)
* directly since these reside on data access layer but instead translates these into business
* layer DTOs (<code>CakeInfo</code>, <code>CakeToppingInfo</code>, <code>CakeLayerInfo</code>)
* 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 (
* <code>CakeInfo</code>, <code>CakeToppingInfo</code>, <code>CakeLayerInfo</code>) to translate
* data between layers. In other words, <code>CakeBakingService</code> cannot return entities (
* <code>Cake</code>, <code>CakeTopping</code>, <code>CakeLayer</code>) directly since these reside
* on data access layer but instead translates these into business layer DTOs (<code>CakeInfo</code>, <code>CakeToppingInfo</code>, <code>CakeLayerInfo</code>) 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
@ -49,6 +48,7 @@ public class App {
/**
* Application entry point
*
* @param args Command line parameters
*/
public static void main(String[] args) {
@ -63,6 +63,7 @@ public class App {
/**
* Initializes the example data
*
* @param cakeBakingService
*/
private static void initializeData(CakeBakingService cakeBakingService) {
@ -76,17 +77,18 @@ public class App {
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)));
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)));
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) {

View File

@ -9,8 +9,7 @@ public class CakeBakingException extends Exception {
private static final long serialVersionUID = 1L;
public CakeBakingException() {
}
public CakeBakingException() {}
public CakeBakingException(String message) {
super(message);

View File

@ -11,6 +11,7 @@ public interface CakeBakingService {
/**
* Bakes new cake according to parameters
*
* @param cakeInfo
* @throws CakeBakingException
*/
@ -18,30 +19,35 @@ public interface CakeBakingService {
/**
* Get all cakes
*
* @return
*/
List<CakeInfo> getAllCakes();
/**
* Store new cake topping
*
* @param toppingInfo
*/
void saveNewTopping(CakeToppingInfo toppingInfo);
/**
* Get available cake toppings
*
* @return
*/
List<CakeToppingInfo> getAvailableToppings();
/**
* Add new cake layer
*
* @param layerInfo
*/
void saveNewLayer(CakeLayerInfo layerInfo);
/**
* Get available cake layers
*
* @return
*/
List<CakeLayerInfo> getAvailableLayers();

View File

@ -31,15 +31,18 @@ public class CakeBakingServiceImpl implements CakeBakingService {
@Override
public void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException {
List<CakeToppingInfo> allToppings = getAvailableToppings();
List<CakeToppingInfo> matchingToppings = allToppings.stream()
.filter((t) -> t.name.equals(cakeInfo.cakeToppingInfo.name)).collect(Collectors.toList());
List<CakeToppingInfo> 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));
throw new CakeBakingException(String.format("Topping %s is not available",
cakeInfo.cakeToppingInfo.name));
}
List<CakeLayer> allLayers = getAvailableLayerEntities();
Set<CakeLayer> foundLayers = new HashSet<>();
for (CakeLayerInfo info : cakeInfo.cakeLayerInfos) {
Optional<CakeLayer> found = allLayers.stream().filter((layer) -> layer.getName().equals(info.name)).findFirst();
Optional<CakeLayer> 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 {
@ -135,8 +138,9 @@ public class CakeBakingServiceImpl implements CakeBakingService {
Iterator<Cake> iterator = cakeBean.findAll().iterator();
while (iterator.hasNext()) {
Cake cake = iterator.next();
CakeToppingInfo cakeToppingInfo = new CakeToppingInfo(cake.getTopping().getId(),
cake.getTopping().getName(), cake.getTopping().getCalories());
CakeToppingInfo cakeToppingInfo =
new CakeToppingInfo(cake.getTopping().getId(), cake.getTopping().getName(), cake
.getTopping().getCalories());
ArrayList<CakeLayerInfo> cakeLayerInfos = new ArrayList<CakeLayerInfo>();
for (CakeLayer layer : cake.getLayers()) {
cakeLayerInfos.add(new CakeLayerInfo(layer.getId(), layer.getName(), layer.getCalories()));

View File

@ -34,7 +34,7 @@ public class CakeInfo {
@Override
public String toString() {
return String.format("CakeInfo id=%d topping=%s layers=%s totalCalories=%d", id.get(), cakeToppingInfo,
cakeLayerInfos, calculateTotalCalories());
return String.format("CakeInfo id=%d topping=%s layers=%s totalCalories=%d", id.get(),
cakeToppingInfo, cakeLayerInfos, calculateTotalCalories());
}
}

View File

@ -25,8 +25,7 @@ public class CakeLayer {
@ManyToOne(cascade = CascadeType.ALL)
private Cake cake;
public CakeLayer() {
}
public CakeLayer() {}
public CakeLayer(String name, int calories) {
this.setName(name);

View File

@ -25,8 +25,7 @@ public class CakeTopping {
@OneToOne(cascade = CascadeType.ALL)
private Cake cake;
public CakeTopping() {
}
public CakeTopping() {}
public CakeTopping(String name, int calories) {
this.setName(name);

View File

@ -4,17 +4,16 @@ package com.iluwatar.lazy.loading;
*
* Lazy loading idiom defers object creation until needed.
* <p>
* This example shows different implementations of the pattern
* with increasing sophistication.
* This example shows different implementations of the pattern with increasing sophistication.
* <p>
* Additional information and lazy loading flavours are described in
* http://martinfowler.com/eaaCatalog/lazyLoad.html
*
*/
public class App
{
public class App {
/**
* Program entry point
*
* @param args command line args
*/
public static void main(String[] args) {

View File

@ -2,8 +2,7 @@ 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 {

View File

@ -2,9 +2,8 @@ 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 {

View File

@ -4,8 +4,8 @@ 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<T>} as {@link Heavy} factory.
* This lazy loader is thread safe and more efficient than {@link HolderThreadSafe}. It utilizes
* Java 8 functional interface {@link Supplier<T>} as {@link Heavy} factory.
*
*/
public class Java8Holder {
@ -23,8 +23,11 @@ public class Java8Holder {
private synchronized Heavy createAndCacheHeavy() {
class HeavyFactory implements Supplier<Heavy> {
private final Heavy heavyInstance = new Heavy();
@Override
public Heavy get() { return heavyInstance; }
public Heavy get() {
return heavyInstance;
}
}
if (!HeavyFactory.class.isInstance(heavy)) {
heavy = new HeavyFactory();

View File

@ -8,7 +8,8 @@ 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.
*/
@ -18,7 +19,8 @@ public class HolderThreadSafeTest {
public void test() throws IllegalAccessException {
HolderThreadSafe hts = new HolderThreadSafe();
{//first call is null
{
// first call is null
Field[] ff = HolderThreadSafe.class.getDeclaredFields();
for (Field f : ff) {
f.setAccessible(true);
@ -30,7 +32,8 @@ public class HolderThreadSafeTest {
// 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
{
// 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);

View File

@ -7,11 +7,9 @@ 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;

View File

@ -2,32 +2,31 @@ 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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) {

View File

@ -11,5 +11,4 @@ public class Hunter extends PartyMemberBase {
public String toString() {
return "Hunter";
}
}

View File

@ -4,22 +4,21 @@ 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).
* <p>
* 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.
* <p>
* 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 {

View File

@ -63,8 +63,7 @@ public class Star {
@Override
public String toString() {
return String.format("%s age: %d years mass: %d tons", type.toString(),
ageYears, massTons);
return String.format("%s age: %d years mass: %d tons", type.toString(), ageYears, massTons);
}
/**

View File

@ -7,7 +7,8 @@ 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;

View File

@ -6,31 +6,31 @@ 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.
* <p>
* 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.
* <p>
* 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
*/

View File

@ -5,20 +5,23 @@ 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.
* <p>
* 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.
* <p>
* 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) {

View File

@ -2,23 +2,24 @@ 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).
* <p>
* 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.
* <p>
* 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) {

View File

@ -5,8 +5,8 @@ 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.
* <p>
* It is responsible for reading and loading the contents of a given file.
*/
@ -27,8 +27,7 @@ public class FileLoader {
*/
public String loadData() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File(
this.fileName)));
BufferedReader br = new BufferedReader(new FileReader(new File(this.fileName)));
StringBuilder sb = new StringBuilder();
String line;
@ -51,6 +50,7 @@ public class FileLoader {
/**
* 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) {

View File

@ -14,11 +14,9 @@ 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.

View File

@ -1,11 +1,10 @@
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.
* <p>
* 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 {
@ -21,6 +20,7 @@ public class FileSelectorPresenter {
/**
* Constructor
*
* @param view The view component that the presenter will interact with.
*/
public FileSelectorPresenter(FileSelectorView view) {
@ -29,6 +29,7 @@ public class FileSelectorPresenter {
/**
* 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) {

View File

@ -1,14 +1,14 @@
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.
* <p>
* 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.
* <p>
* 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 {

View File

@ -1,8 +1,8 @@
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 {
@ -23,6 +23,7 @@ public interface FileSelectorView {
/**
* Sets the presenter component, to the one given as parameter.
*
* @param presenter The new presenter component.
*/
public void setPresenter(FileSelectorPresenter presenter);
@ -34,6 +35,7 @@ public interface FileSelectorView {
/**
* Sets the file's name, to the value given as parameter.
*
* @param name The new name of the file.
*/
public void setFileName(String name);
@ -45,12 +47,14 @@ public interface FileSelectorView {
/**
* 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);

View File

@ -10,8 +10,8 @@ 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 {
@ -67,8 +67,8 @@ public class FileSelectorPresenterTest {
}
/**
* Tests if we receive a confirmation when we attempt to open a file that
* it's name is null or an empty string.
* 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() {
@ -83,8 +83,7 @@ public class FileSelectorPresenterTest {
}
/**
* Tests if we receive a confirmation when we attempt to open a file that it
* doesn't exist.
* Tests if we receive a confirmation when we attempt to open a file that it doesn't exist.
*/
@Test
public void fileConfirmationWhenFileDoesNotExist() {

View File

@ -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);
}
}

View File

@ -2,20 +2,20 @@ 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.
* <p>
* 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) {

View File

@ -5,8 +5,7 @@ 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 {

View File

@ -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
* 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.
* 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,16 +21,14 @@ 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)
@Action(
semantics = SemanticsOf.SAFE
)
@Action(semantics = SemanticsOf.SAFE)
@HomePage
public HomePageViewModel homePage() {
return container.injectServicesInto(new HomePageViewModel());

View File

@ -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
* 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.
* 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;
@ -32,6 +28,7 @@ public class HomePageViewModel {
public String title() {
return getObjects().size() + " objects";
}
// endregion
// region > object (collection)
@ -39,6 +36,7 @@ public class HomePageViewModel {
public List<SimpleObject> getObjects() {
return simpleObjects.listAll();
}
// endregion
// region > injected services

View File

@ -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
* 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.
* 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,34 +33,19 @@ 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 "
@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.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<SimpleObject> {
@ -72,6 +53,7 @@ public class SimpleObject implements Comparable<SimpleObject> {
public TranslatableString title() {
return TranslatableString.tr("Object: {name}", "name", getName());
}
// endregion
// region > name (property)
@ -80,9 +62,7 @@ public class SimpleObject implements Comparable<SimpleObject> {
@javax.jdo.annotations.Column(allowsNull = "false", length = 40)
@Title(sequence = "1")
@Property(
editing = Editing.DISABLED
)
@Property(editing = Editing.DISABLED)
public String getName() {
return name;
}
@ -96,18 +76,15 @@ public class SimpleObject implements Comparable<SimpleObject> {
// region > updateName (action)
public static class UpdateNameDomainEvent extends ActionDomainEvent<SimpleObject> {
public UpdateNameDomainEvent(final SimpleObject source, final Identifier identifier, final Object... arguments) {
public UpdateNameDomainEvent(final SimpleObject source, final Identifier identifier,
final Object... arguments) {
super(source, identifier, arguments);
}
}
@Action(
domainEvent = UpdateNameDomainEvent.class
)
@Action(domainEvent = UpdateNameDomainEvent.class)
public SimpleObject updateName(
@Parameter(maxLength = 40)
@ParameterLayout(named = "New name")
final String name) {
@Parameter(maxLength = 40) @ParameterLayout(named = "New name") final String name) {
setName(name);
return this;
}
@ -126,6 +103,7 @@ public class SimpleObject implements Comparable<SimpleObject> {
public Long getVersionSequence() {
return (Long) JDOHelper.getVersion(this);
}
// endregion
// region > compareTo

View File

@ -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
* 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.
* 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;
@ -42,54 +38,40 @@ public class SimpleObjects {
public TranslatableString title() {
return TranslatableString.tr("Simple Objects");
}
// endregion
// region > listAll (action)
@Action(
semantics = SemanticsOf.SAFE
)
@ActionLayout(
bookmarking = BookmarkPolicy.AS_ROOT
)
@Action(semantics = SemanticsOf.SAFE)
@ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT)
@MemberOrder(sequence = "1")
public List<SimpleObject> listAll() {
return container.allInstances(SimpleObject.class);
}
// endregion
// region > findByName (action)
@Action(
semantics = SemanticsOf.SAFE
)
@ActionLayout(
bookmarking = BookmarkPolicy.AS_ROOT
)
@Action(semantics = SemanticsOf.SAFE)
@ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT)
@MemberOrder(sequence = "2")
public List<SimpleObject> findByName(
@ParameterLayout(named="Name")
final String name
) {
return container.allMatches(
new QueryDefault<>(
SimpleObject.class,
"findByName",
"name", name));
public List<SimpleObject> 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<SimpleObjects> {
public CreateDomainEvent(final SimpleObjects source, final Identifier identifier, final Object... arguments) {
public CreateDomainEvent(final SimpleObjects source, final Identifier identifier,
final Object... arguments) {
super(source, identifier, arguments);
}
}
@Action(
domainEvent = CreateDomainEvent.class
)
@Action(domainEvent = CreateDomainEvent.class)
@MemberOrder(sequence = "3")
public SimpleObject create(
final @ParameterLayout(named="Name") String name) {
public SimpleObject create(final @ParameterLayout(named = "Name") String name) {
final SimpleObject obj = container.newTransientInstance(SimpleObject.class);
obj.setName(name);
container.persistIfNotAlready(obj);

View File

@ -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
*
* 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;

View File

@ -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
*
* 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;

View File

@ -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
* 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.
* 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;
@ -33,12 +29,10 @@ import domainapp.fixture.scenarios.RecreateSimpleObjects;
public class DomainAppFixturesProvider implements FixtureScriptsSpecificationProvider {
@Override
public FixtureScriptsSpecification getSpecification() {
return FixtureScriptsSpecification
.builder(DomainAppFixturesProvider.class)
return FixtureScriptsSpecification.builder(DomainAppFixturesProvider.class)
.with(FixtureScripts.MultipleExecutionStrategy.EXECUTE)
.withRunScriptDefault(RecreateSimpleObjects.class)
.withRunScriptDropDown(FixtureScriptsSpecification.DropDownPolicy.CHOICES)
.withRecreate(RecreateSimpleObjects.class)
.build();
.withRecreate(RecreateSimpleObjects.class).build();
}
}

View File

@ -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
* 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.
* 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;
@ -28,6 +24,7 @@ public class SimpleObjectCreate extends FixtureScript {
// region > name (input)
private String name;
/**
* Name of the object (required)
*/
@ -39,6 +36,7 @@ public class SimpleObjectCreate extends FixtureScript {
this.name = name;
return this;
}
// endregion
@ -47,11 +45,13 @@ public class SimpleObjectCreate extends FixtureScript {
/**
* The created simple object (output).
*
* @return
*/
public SimpleObject getSimpleObject() {
return simpleObject;
}
// endregion
@Override

View File

@ -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
* 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.
* 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;

View File

@ -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
* 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.
* 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,8 +29,8 @@ import domainapp.fixture.modules.simple.SimpleObjectsTearDown;
public class RecreateSimpleObjects extends FixtureScript {
public final List<String> NAMES = Collections.unmodifiableList(Arrays.asList(
"Foo", "Bar", "Baz", "Frodo", "Froyo", "Fizz", "Bip", "Bop", "Bang", "Boo"));
public final List<String> NAMES = Collections.unmodifiableList(Arrays.asList("Foo", "Bar", "Baz",
"Frodo", "Froyo", "Fizz", "Bip", "Bop", "Bang", "Boo"));
public RecreateSimpleObjects() {
withDiscoverability(Discoverability.DISCOVERABLE);
@ -54,6 +50,7 @@ public class RecreateSimpleObjects extends FixtureScript {
this.number = number;
return this;
}
// endregion
// region > simpleObjects (output)
@ -65,6 +62,7 @@ public class RecreateSimpleObjects extends FixtureScript {
public List<SimpleObject> getSimpleObjects() {
return simpleObjects;
}
// endregion
@Override
@ -75,7 +73,8 @@ public class RecreateSimpleObjects extends FixtureScript {
// validate
if (number < 0 || number > NAMES.size()) {
throw new IllegalArgumentException(String.format("number must be in range [0,%d)", NAMES.size()));
throw new IllegalArgumentException(String.format("number must be in range [0,%d)",
NAMES.size()));
}
//

View File

@ -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
* 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.
* 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;
@ -45,7 +41,8 @@ public class SimpleAppSystemInitializer {
}
private static IsisConfiguration testConfiguration() {
final IsisConfigurationForJdoIntegTests testConfiguration = new IsisConfigurationForJdoIntegTests();
final IsisConfigurationForJdoIntegTests testConfiguration =
new IsisConfigurationForJdoIntegTests();
testConfiguration.addRegisterEntitiesPackagePrefix("domainapp.dom.modules");
return testConfiguration;

View File

@ -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
*
* 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;

View File

@ -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
*
* 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;
@ -27,5 +25,4 @@ public class CatalogOfFixturesGlue extends CukeGlueAbstract {
public void integrationFixtures() throws Throwable {
scenarioExecution().install(new RecreateSimpleObjects());
}
}

View File

@ -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
*
* 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;

View File

@ -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
*
* 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;
@ -26,14 +24,9 @@ import cucumber.api.junit.Cucumber;
* Runs scenarios in all <tt>.feature</tt> 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
}

View File

@ -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
* 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.
* 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
*
* <p>
* See:
*
* <pre>
* &lt;filter>
* &lt;filter-name>wicket&lt;/filter-name>
@ -95,10 +92,13 @@ public class SimpleApplication extends IsisWicketApplication {
}
// else demo mode
final AuthenticatedWebSessionForIsis s = (AuthenticatedWebSessionForIsis) super.newSession(request, response);
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");
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;
}
@ -129,11 +129,15 @@ public class SimpleApplication extends IsisWicketApplication {
@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("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")));
bind(InputStream.class).annotatedWith(Names.named("metaInfManifest")).toProvider(
Providers.of(getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF")));
}
};
@ -142,7 +146,9 @@ public class SimpleApplication extends IsisWicketApplication {
private static String readLines(final Class<?> contextClass, final String resourceName) {
try {
List<String> readLines = Resources.readLines(Resources.getResource(contextClass, resourceName), Charset.defaultCharset());
List<String> readLines =
Resources.readLines(Resources.getResource(contextClass, resourceName),
Charset.defaultCharset());
final String aboutText = Joiner.on("\n").join(readLines);
return aboutText;
} catch (IOException e) {

Some files were not shown because too many files have changed in this diff Show More