How to log when using Command Pattern - java

Head First Design Patterns say:
The Command Pattern encapsulates a request as an object, thereby
letting you parameterize other objects with different requests, queue
or log requests, and support undoable operations.
Later the book said:
The semantics of some applications require that we log all actions and
be able to recover after a crash by reinvoking those actions. The
Command Pattern can support these semantics with the addition of two
methods: store() and load(). In Java we could use object serialization
to implement these methods, but the normal caveats for using
serialization for persistence apply.
How does this work? As we execute commands, we store a history of them
on disk. When a crash occurs, we reload the command objects and invoke
their execute() methods in batch and in order.
I am trying to come up with an example code. The code I wrote till now is:
class Client {
public static void main(String[] args) {
Command enableCommand = new EnableCommand();
enableCommand.execute();
}
}
interface Command {
void execute();
void store();
void load();
}
class EnableCommand implements Command {
public EnableCommand() {
}
#Override
public void execute() {
store();
System.out.println("Execute Command");
}
#Override
public void store() {
System.out.println("Storing on Disk");
}
#Override
public void load() {
// TODO Auto-generated method stub
}
}
How the load() function is supposed to work?

Related

Execute a method asynchronously using a WokManager

My question is simple, how can I execute a method in java using the Weblogic WorkManager?
I don't want to use any Thread method of implementation.
Example:
public class CallerClass {
public void callerMethod() {
// Execution
// Launch method in new thread
obj.asyncMethod();
// Continue before finishing ayncMethod
return;
}
public void asyncMethod() {
// Asynchronous method
}
}
See if this helps, i find it useful.
using-the-weblogic-work-manager-to-delegate-long-running-tasks

How do you get event notifications back to the main program class of a Java console app?

I'm coming to Java from C#, and I'm really just trying to figure out how to do things in Java world. I'm running Java 8 in IntelliJ IDEA. I found this explaining events in Java as basically being hand-made through manual registration and an interface method call. The code example has enough problems that I assume it was never compiled. After cleaning that up a bit I have this:
Interface MetronomeEvent:
public interface MetronomeEvent {
void Tick(Date tickDate);
}
Class EventFiringSource:
public class EventFiringSource {
// Our collection of classes that are subscribed as listeners of our
protected List<MetronomeEvent> _listeners=new ArrayList();
// Method for listener classes to register themselves
public void addMetronomeEventListener(MetronomeEvent listener)
{
_listeners.add(listener);
}
// "fires" the event
protected void fireMetronomeEvent()
{
if (_listeners != null && !_listeners.isEmpty())
{
for (MetronomeEvent e:_listeners)
{
e.Tick(new Date());
}
}
}
public void Start()
{
fireMetronomeEvent();
}
}
Main console application:
public class MainApp implements MetronomeEvent {
public static void main(String[] args) {
EventFiringSource source = new EventFiringSource();
source.addMetronomeEventListener(this); // Adds itself as a listener for the event
source.Start();
}
public void Tick(Date tickDate)
{
System.out.println(tickDate.toString());
}
}
The one remaining error is source.addMetronomeEventListener(this); where the compiler complains that it cannot reference MyApp.this from a static context. That makes sense, but I don't see any way then that I could, after implementing the MetronomeEvent interface on the main program class, actually pass it to source.addMetronomeEventListener() for registration. Is it impossible to directly register the main program class for events? Am I supposed to create and register a Listener class that implements MetronomeEvent and will act on behalf of the main application? Like this?
public class Listener implements MetronomeEvent {
public void Tick(Date tickDate){
System.out.println(tickDate.toString());
}
}
And then:
public static void main(String[] args) {
EventFiringSource source = new EventFiringSource();
Listener l=new Listener();
source.addMetronomeEventListener(l); // Adds another object to listen on behalf of main()
source.Start();
}
This is not about events, it's about main() and static methods in general.
I would suggest writing your main() as
public static void main(String[] args) {
new MainApp(args).execute();
}
This way you're immediately jumping from static function world into object-oriented world.
Based on Vince Emigh's comment/answer I was led to this Oracle doc on lamda expressions and to this one on method references. I've found 3 ways to do this so far.
1) Anonymous class:
source.addMetronomeEventListener(
new MetronomeEvent() {
#Override
public void Tick(Date tickDate) {
System.out.println("anonymous class:");
System.out.println(tickDate.toString());
}
}
); // Adds itself as a listener for the event
2) Lambda expression:
source.addMetronomeEventListener(d -> System.out.println("lambda:\n"+d.toString()));
3) Method reference, which is the closest to what I am accustomed to. A method is defined in the main class:
public static void processTick(Date tickDate){
System.out.println("method reference:");
System.out.println(tickDate.toString());
}
...and then in the body of main() it is added as an event handler like this:
source.addMetronomeEventListener(MainApp::processTick);

Is there any OOB Command interfaces in Java 1.6 for lambda-like sentences?

Sorry if this was asked, but I keep wondering and weren't able to google up solution and not for luck of trying.
When implementing Command pattern inside one class, this one-method interface keeps popping up in all places.
public interface Command {
void execute();
}
Then it gets reused plenty of times like this:
public void doAction1()
{
perform(new Command () {
#Override
public void execute()
{
//do some crazy stuff
}
});
}
public void doAction2()
{
perform(new Command () {
#Override
public void execute()
{
//do some event crazier stuff
}
});
}
public void doAction3()
{
perform(new Command () {
#Override
public void execute()
{
//do a barrel roll
}
});
}
private void perform(Command command)
{
command.execute();
}
Different namings, different modules, different software even --- but this one gets reimplemented over and over, cluttering source and doing essentially nothing new.
Is there any generic, OOB one-method interface that's OK to use instead of creating my own every time I need lambda-like sentence? Is it OK to use Runnable in this way? Wouldn't it create confusion in the mind of some future source code-reader?
PS: Now, I know, that there's java 1.8 with lambdas and all, but at my work we're stuck with 1.6 for the moment (enterprise customers are so enterprise), so I'd appreciate some archeological help here.
Yes, Runnable or Callable (if you need to return a result) are perfectly fine to use.

Java SecurityManager #Override public void checkPermission(Permission perm)

I'm building a SWING application and also need to write a custom SecurityManager. If I write an empty class which extends SecurityManager like this
public class Sandbox extends SecurityManager {}
it works fine, meaning that the GUI is rendered correctly and all privileges like I/O are revoked.
However I need to customize the checkPermission method and whenever I override it nothing works anymore...
Why even something like this shouldn't work??
public class Sandbox extends SecurityManager {
#Overide
public void checkPermission(Permission perm) {
super.checkPermission(perm);
}
}
Update: a very basic example that shows the problem is this
public static void main(String[] args) {
System.setSecurityManager(new SecurityManager() {
#Override
public void checkPermission(Permission p) {
if (some_condition_here) {
// Do something here
} else {
// Resort to default implementation
super.checkPermission(p);
}
}
});
new JFrame().setVisible(true);
}
Removing the "checkPermission" method the application works correctly, but I really can't get my head around this.
The permissions are granted based on all the code on the stack. All callers must have the required permission. If you override the method and call the superclass method, your code is on the stack as well which implies that your codebase (where your custom SecurityManager belongs to) must have the permission you (your callers) ask for.
That’s the difference between overriding or not. If you don’t override that method only the (possibly privileged) caller’s code is on the stack and it will get the requested permission. If you override that method your code is also on the stack and must have the permission as well.
So if you want to implement a custom SecurityManager which invokes the inherited check method you must configure the inherited (policy based) logic to give your SecurityManager all permissions it should be able to grant. It’s recommended to separate the SecurityManager from the rest of the application into a different codebase so only the SecurityManager and nothing else gets the generous permissions.
If you call the superclass' checkPermission(p) you didn't have to override the class in the first place. Comment it out, then it works.
The superclas' calls java.security.AccessController.checkPermission(perm) and that seems to throw a java.security.AccessControlException, when not invoked by java.lang.SecurityManager
in my case it says:
Could not load Logmanager "null"
java.security.AccessControlException: access denied (java.util.PropertyPermission java.util.logging.manager read)
etc.
public class SecurityManagerExample
{
public static void main(String[] args)
{
System.setSecurityManager(new SecurityManager()
{
#Override
public void checkPermission(Permission p)
{
//super.checkPermission(p);
}
});
new JFrame().setVisible(true);
}
}
I found a tutorial on how to write a security manager. I'd also recommend you to go through the java doc and the examples provided by oracle.
UPDATE
Take a look at the method summary and override the functionality you want to forbid.
As I found out you also need to explicitly allow the functionality you want to have.
Here an example:
public class SecurityManagerExample
{
public static void main(String[] args)
{
System.setSecurityManager(new SecurityManager()
{
#Override
public void checkWrite(String file) {
// no exception is thrown, i. e. creating files is allowed in general
}
#Override
public void checkDelete(String file)
{
if (file.equals("test.xml"))
{
throw new SecurityException("Not allowed to delete test.xml!");
}
}
});
File f = new File("test.xml");
try
{
f.createNewFile();
}
catch (IOException e)
{
}
f.delete();
}
}
OUTPUT
Exception in thread "main" java.lang.SecurityException: Not allowed to delete test.xml!
at main.SecurityManagerExample$1.checkDelete(SecurityManagerExample.java:60)
at java.io.File.delete(File.java:902)
at main.SecurityManagerExample.main(SecurityManagerExample.java:74)

Using Command Design pattern

Can anyone explain with a simple example the Command Pattern? I tried searching on the internet, but I got confused.
public interface Command {
public void execute();
}
For the most part, commands are immutable and contain instructions that encapsulate a single action that is executed on demand. You might also have a RuntimeCommand that accepts instructions upon execution, but this delves more into the Strategy or Decorator Patterns depending on the implementations.
In my own opinion, I think it's very important to heed the immutable context of a command otherwise the command becomes a suggestion. For instance:
public final class StopServerCommand implements Command {
private final Server server;
public StopServerCommand(Server server) { this.server = server; }
public void execute() {
if(server.isRunning()) server.stop();
}
}
public class Application {
//...
public void someMethod() {
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(Event e) {
stopCommand.execute();
}
});
}
}
I personally don't really like commands. In my own experience, they only work well for framework callbacks.
If it helps, think of a command in a metaphorical sense; a trained soldier is given a command by his/her commanding officer, and on demand the soldier executes this command.
You can think of Command pattern workflow as follows.
Client calls Invoker => Invoker calls ConcreteCommand => ConcreteCommand calls Receiver method, which implements abstract Command method.
UML Diagram from dofactory article:
Key features:
Command declares an interface for all commands, providing a simple execute() method which asks the Receiver of the command to carry out an operation.
The Receiver has the knowledge of what to do to carry out the request.
The Invoker holds a command and can get the Command to execute a request by calling the execute method.
The Client creates ConcreteCommands and sets a Receiver for the command.
The ConcreteCommand defines a binding between the action and the receiver.
When the Invoker calls execute the ConcreteCommand will run one or more actions on the Receiver.
Code snippet:
interface Command {
void execute();
}
interface Receiver {
public void switchOn();
}
class OnCommand implements Command{
private Receiver receiver;
public OnCommand(Receiver receiver){
this.receiver = receiver;
}
public void execute(){
receiver.switchOn();
}
}
class Invoker {
private Command command;
public Invoker(Command command){
this.command = command;
}
public void execute(){
this.command.execute();
}
}
class TV implements Receiver{
public void switchOn(){
System.out.println("Switch on from TV");
}
}
class DVDPlayer implements Receiver{
public void switchOn(){
System.out.println("Switch on from DVDPlayer");
}
}
public class CommandDemoEx{
public static void main(String args[]){
// On command for TV with same invoker
Receiver receiver = new TV();
Command onCommand = new OnCommand(receiver);
Invoker invoker = new Invoker(onCommand);
invoker.execute();
// On command for DVDPlayer with same invoker
receiver = new DVDPlayer();
onCommand = new OnCommand(receiver);
invoker = new Invoker(onCommand);
invoker.execute();
}
}
output:
Switch on from TV
Switch on from DVDPlayer
Explanation:
In this example,
Command interface defines execute() method.
OnCommand is ConcreteCommand, which implements execute() method.
Receiver is an interface and implementers have to provide implementation for the methods.
TV and DVDPlayer are two types of Receivers, which are passed to ConcreteCommand like OnCommand.
Invoker contains Command. It's the key to de-couple Sender from Receiver.
Invoker receives OnCommand -> which calls Receiver (TV) to execute this command.
By using Invoker, you can switch on TV and DVDPlayer. If you extend this program, you switch off both TV and DVDPlayer too.
You can use Command pattern to
Decouple the sender & receiver of command
Implement callback mechanism
Implement undo and redo functionality
Maintain a history of commands
Have a look at this dzone and journaldev and Wikipedia articles.
Source code as Wikipedia page is simple, cleaner and self explanatory.
You can implement Undo and Redo if you follow the steps as quoted in this article
Here is another example you can use to understand how command pattern works, using real life scenarios: You cannot travel from one place to another by airplane without using the command pattern!
If you are a frequent traveler, all you care about as a client is to travel from where you are to another . you don't care about how the pilot will fly the plane or which airline will be available .. you cant really predict that. all you want is to get the the air port and tell them to take you to your destination.
But if you do that, your command to the airport authorities will be laughed at! they need you to supply a command object, which is your ticket. as much as you don't care about which airline or which plane type, when you are ready to fly, you need to supply a ticket command object. The invoker, which is the airport officials needs to check your command (ticket) so that they can validate it, undo it if it is fake, redo it if they made a mistake (without you having to go through the booking process all over).
In short , they want to have complete control of your command (ticket) before deciding whether or not to invoke or execute your command, which lets the airline (the receiver ) execute ( put you on a plane and take you to your destination) .
Mind you, your command (your ticket) already has the information of the receiver (airline) without which the airport officials wont even start to process your ticket in the first place.
The airport authorities could even have a bunch of tickets they are working on. they may choose to delay my ticket and let someone that came after me go through (invoke another persons ticket before mine)
Here is the code :
[TestClass]
public class Client
{
[TestMethod]
public void MyFlight_UsingCommandPattern()
{
var canadianAirline = new Airline();
AirlineTicket_Command myTicket = new MyAirLineTicket(canadianAirline);
var airportOfficials = new AirportOfficials_Invoker(myTicket);
airportOfficials.ProcessPasengerTicket_And_AllowPassengerToFly_Execute();
//assert not implemented
}
}
public class AirportOfficials_Invoker
{
private AirlineTicket_Command PassengerTicket { set; get; }
public AirportOfficials_Invoker(AirlineTicket_Command passengerTicket)
{
throw new NotImplementedException();
}
public void ProcessPasengerTicket_And_AllowPassengerToFly_Execute()
{
PassengerTicket.Execute();
}
}
public abstract class AirlineTicket_Command
{
protected Airline Airline { set; get; }
protected AirlineTicket_Command(Airline airline)
{
Airline = airline;
}
public abstract void Execute();
}
public class MyAirLineTicket : AirlineTicket_Command
{
public MyAirLineTicket(Airline airline)
: base(airline)
{
}
public override void Execute()
{
Airline.FlyPassenger_Action();
}
}
public class Airline
{
public void FlyPassenger_Action()
{
//this will contain all those stuffs of getting on the plane and flying you to your destination
}
}
My requirement is to perform a sequence of tasks (which can be re-used in several Usecases) each with its own exception flow. Found Command pattern's implementation logical here.
I am trying to make it like each action executed by the command (whether normal/alternate flow) can be an exception handler too. However, If the command is registered with another handler then this should be used. Any suggestions for improvement/correction are welcome.
public interface Command {
Result run() throws Exception;
Command onException(ExceptionHandler handler);
}
public class Result {
}
public interface ExceptionHandler {
void handleException(Exception e);
}
public interface Action {
Result execute() throws Exception;
}
public class BasicCommand implements Command {
private Action action;
private ExceptionHandler handler;
public BasicCommand(Action action) {
if (action == null) {
throw new IllegalArgumentException("Action must not be null.");
}
this.action = action;
this.handler = (ExceptionHandler) this.action;
}
#Override
public Command onException(ExceptionHandler handler) {
if (handler != null) {
this.handler = handler;
}
return this;
}
public Result run() throws Exception {
Result result = null;
try {
result = action.execute();
} catch (Exception e) {
handler.handleException(e);
}
return result;
}
}
public class BasicAction implements Action, ExceptionHandler {
private Object[] params;
public BasicAction(Object... params) {
this.params = params;
}
#Override
public Result execute() throws Exception {
// TODO Auto-generated method stub
return null;
}
#Override
public void handleException(Exception e) {
// TODO exception translation: prepare unchecked application. exception and throw..
}
}
public class Main {
public static void main(String[] args) throws Exception {
int param1 = 10;
String param2 = "hello";
// command will use the action itself as an exception handler
Result result = new BasicCommand(new BasicAction(param1, param2)).run();
ExceptionHandler myHandler = new ExceptionHandler(){
#Override
public void handleException(Exception e) {
System.out.println("handled by external handler");
}
};
// command with an exception handler passed from outside.
Result result2 = new BasicCommand(new BasicAction(param1, param2)).onException(myHandler).run();
}
}
Command Design Patterns decouples invoker of service and provider of service. In general scenario, say for eg., If Object A wants service of Object B, it'll directly invoke B.requiredService(). Thus, A is aware about B. In Command pattern, this coupling is removed. Here, there's an intermediate object known as Command, which comes into picture. Thus, A deals with Command object and command object deals with actual object B. This approach has several applications such as designing applications, which are :-
Accepts commands as requests.
Undoing requests.
Requests requests.
Creating macros.
Creating Task Executors and Task Managers.
For more information regarding, Command Design Pattern, I'll recommend https://en.wikipedia.org/wiki/Command_pattern.
For all other design patterns, refer to https://www.u-cursos.cl/usuario/.../mi_blog/r/head_first_design_patterns.pdf
I would try to give you another rough analogy here.
Suppose that one day God calls on you and tells you that the world's in danger and He needs your help to save it. Further helping you , He tells you that He has sent some superheroes on earth.
Since He doesn't know oops and hence He doesn't call them superheroes (doesn't provide you any interface or abstract class over them) but just tell you their names for ex - batman, superman, iron man and the powers they have.
He also says that in future He might send more such guys in future.
Now He assigns you special responsibility -> control them and for that provides you with seven hands. He doesn't fixes the task of each hand Himself but leaves it on you.
You want flexibility in assigning any hand control of any superhero's power and don't want to repeatedly change things through multiple conditions.
You are in a fix. What do you do now?
Enter Command Pattern.
Create an interface Command and has only one method execute() in it. Encapsulate every power of each superhero and make that implement Command for ex - IronManCreatesSuitCommand
Now you can assign any hand to any command at any time giving you lot more flexibility because now none of your hands cares about the specific task it has to do. You just assign it any command to it. It calls execute on it and the command takes care of everything else.
Now even when God sends any other superhero with different powers, you know what to do.

Categories