I am creating a board game with Project RedDwarf framework (old project DarkStar).
My question is this:
I need to have commands sent back and forth from the server to the client and reverse, and I need a solid programming architecture to incorporate on the command messaging service.
I thought of having a Command interface, and each subcommand would be an implementation of it (which holds the command String).
For instance lets say we need to check if a user is online. We have an interface called Command, then an interface called Check which extends Command, and finally we have the implementation called OnlineCheck.
OnlineCheck could have a method called getCommand and would return the commands String.
Ok till now.. BUT what I really wanna do is, include the possible replies on the same implementation class, so that I can check what the client replied to me, based on one of the pre defined replies.
How should I go about doing this?
Firstly, appreciate the use of command pattern.
OnlineCheck could have a method called getCommand and would return the commands String.
Command interface should have an entry point like execute() or run() that would implement what OnlineCheck should do. So there needn't be any getCommand() that in turn returns the command string which again needs to be interpreted.
Once you go down this path, the command instance (an instance of OnlineCheck in this case) could hold the response and can be sent back to the client. The client in turn would give this response back to the code block that generated it as it would be the best one to know what type of responses to expect for this command and can interpret them appropriately.
My two cents!
Related
Going through the Command design pattern I understand that we need to create a Command by setting the context via constructor and then calling the execute method to perform some action on the context. Example:
public class Command implements ICommand {
Device device;
public Command(Device device) {
this.device = device;
}
public void execute() {
this.device.turnOn()
}
}
I was wondering that with this approach we will be required to create a new Command object for every device object we create. Will it be ok to pass the context and some parameters to the execute method? I am looking for something like:
public class Command implements ICommand {
public void execute(Device device) {
this.device.turnOn();
}
}
Are there any issues with this approach?
The idea behind the Command pattern is that it should encapsulate all the information needed to perform an action. This lets you do things like delay the execution of the action until a later time, or even undo the action after it has been executed.
For a concrete example, consider the "Undo" feature in a word processor.
Each time you type in the document, the application uses the Command pattern to record the action.
If you hit "Undo", the text you typed disappears.
Then, when you hit "Redo", the typed text reappears, without the application needing to ask for the input again. It does this by replaying the command that it stored in step 1, which contains all the information about the text you typed.
If your command object requires additional parameters in order to perform the action, it doesn't really implement the Command pattern. It loses most of the advantages of the Command pattern, because the caller can't execute the action without additional information. In your example, the caller would need to know which device is being turned on.
However, that doesn't mean that you have to stick rigidly to the pattern. If it's more useful in your case for the execute method to accept a Device parameter, that's what you should do! If you do that, you should consider renaming the interface, though. Referring to it as a Command pattern when it doesn't follow the pattern exactly could confuse other readers of the code.
When deciding whether to take an object in as a method parameter or a constructor parameter, one of the things I find most helpful is to consider how I'm going to test the application. Objects that form part of the initial setup of the test get passed in as constructor parameters, while objects that form the inputs of the test, or the test vector, are method parameters. I find that following that guideline helps to produce maintainable code.
I want to run MapReduceIndexerTool from Java.
Right now I do it from command line using hadoop jar as you can see here, but I want to check it's status (to see if it's finalized, in progress, etc.) from Java code.
So basically I want to run it from Java in order to be able to check it's status from Java. Is there a way to run it from command line and check it's status from Java?
Also, there is a way to make Map Reduce to send an event (on a callback for example) when a job is completed? Something like a webhook?
As far as I know Tool interface exposes only int run(String[] args) method, so in general you would create new instance, form proper argument string and call that method.
From other hand, MapReduceIndexerTool has int run(Options options) method, that could be used to run it without forming shell-style argument. However, this method is protected, so this will need to have calling class to be created in same package as MapReduceIndexerTool.
Yes, this question is for a bot, but it requires little knowledge of bots. So please, don't be put off by that.
This question may seem similar to other PircBot questions, but bear with me, it isn't.
So, I've recently been working on an IRC bot based off of PircBot, and I've come upon a snag. I have a rapidly growing command list, and currently I'm using a horribly inefficient and very ugly block of these:
if(message.equalsIgnoreCase("!thatcommand"))
processMessage(channel,"returnforthatcommand"+sender);
I have a huge block of these where it just checks the message time after time for if it matches. That's my main problem. The process message method just sends the message after checking if I'm running the logger (printing the message to the console).
What I really want to do is to streamline it. I want to make some sort of chart, like a HashMap, that will process the strings accordingly. I've also considered making a Command class that stores the response and a boolean that tells whether or not a chatter has to be "opped" to use it. I've tried making files and started making a few attempts at HashMaps, but I could really use some direction on the simplest and/or most efficient way to go about this. I do have a few different "modes" for the bot, so making separate HashMaps for different privilege levels may be a good option.
One last thing: I later want to put the bot into a Jar file with a GUI for outside running (Eclipse takes ages to start up on this laptop), and I want to be able to make permanent changes to the command list through the bot itself as opposed to recoding it... That's why I was considering trying to reference a file, but then I had tons of problems with the program not being able to find said file.
Any suggestions?
Alright, for the people that don't like reading long things: I have sets of data that are called by a trigger String (message) and return a certain response String. How can I store these and call them in the simplest fashion, and how can I make it so that I can write things onto the list on the fly?
You could the use the Abstract Factory design pattern. It would be something like this:
public abstract class CommandFactory {
private static Map<String,Command> commands;
public static Command getInstance(String commandName) {
if (commands == null) initialize();
return commands.get(commandName);
}
private static void initialize() {
commands.put("commandA", new CommandA());
commands.put("commandB", new CommandB());
}
}
And write CommandFactory.getInstance("commandString") in the place of your if clauses.
Suggestion: Hashtable of objects implementing an interface which includes a method such as execute(). Use the hashtable to go from command to object, call its execute, done.
Yes, you'll need to initialize that table as your server starts up. Whether you do that from literal strings or have each actor announce its own keyword is up to you. The latter's probably more elegant but doesn't permit aliases.
I'll give a brief overview of my goals below just in case there are any better, alternative ways of accomplishing what I want. This question is very similar to what I need, but not quite exactly what I need. My question...
I have an interface:
public interface Command<T> extends Serializable {}
..plus an implementation:
public class EchoCommand implements Command<String> {
private final String stringToEcho;
public EchoCommand(String stringToEcho) {
this.stringToEcho = stringToEcho;
}
public String getStringToEcho() {
return stringToEcho;
}
}
If I create another interface:
public interface AuthorizedCommand {
String getAuthorizedUser();
}
..is there a way I can implement the AuthorizedCommand interface on EchoCommand at runtime without knowing the subclass type?
public <C extends Command<T>,T> C authorize(C command) {
// can this be done so the returned Command is also an
// instance of AuthorizedCommand?
return (C) theDecoratedCommand;
}
The why... I've used Netty to build myself a very simple proof-of-concept client / server framework based on commands. There's a one-to-one relationship between a command, shared between the client and server, and a command handler. The handler is only on the server and they're extremely simple to implement. Here's the interface.
public interface CommandHandler<C extends Command<T>,T> {
public T execute(C command);
}
On the client side, things are also extremely simple. Keeping things simple in the client is the main reason I decided to try a command based API. A client dispatches a command and gets back a Future. It's clear the call is asynchronous plus the client doesn't have deal with things like wrapping the call in a SwingWorker. Why build a synchronous API against asynchronous calls (anything over the network) just to wrap the synchronous calls in an asynchronous helper methods? I'm using Guava for this.
public <T> ListenableFuture<T> dispatch(Command<T> command)
Now I want to add authentication and authorization. I don't want to force my command handlers to know about authorization, but, in some cases, I want them to be able to interrogate something with regards to which user the command is being executed for. Mainly I want to be able to have a lastModifiedBy attribute on some data.
I'm looking at using Apache Shiro, so the obvious answer seems to be to use their SubjectAwareExecutor to get authorization information into ThreadLocal, but then my handlers need to be aware of Shiro or I need to abstract it away by finding some way of mapping commands to the authentication / authorization info in Shiro.
Since each Command is already carrying state and getting passed through my entire pipeline, things are much simpler if I can just decorate commands that have been authorized so they implement the AuthorizedCommand interface. Then my command handlers can use the info that's been decorated in, but it's completely optional.
if(command instanceof AuthorizedCommand) {
// We can interrogate the command for the extra meta data
// we're interested in.
}
That way I can also develop everything related to authentication / authorization independent of the core business logic of my application. It would also (I think) let me associate session information with a Netty Channel or ChannelGroup which I think makes more sense for an NIO framework, right? I think Netty 4 might even allow typed attributes to be set on a Channel which sounds well suited to keeping track of things like session information (I haven't looked into it though).
The main thing I want to accomplish is to be able to build a prototype of an application very quickly. I'd like to start with a client side dispatcher that's a simple map of command types to command handlers and completely ignore the networking and security side of things. Once I'm satisfied with my prototype, I'll swap in my Netty based dispatcher (using Guice) and then, very late in the development cycle, I'll add Shiro.
I'd really appreciate any comments or constructive criticism. If what I explained makes sense to do and isn't possible in plain old Java, I'd consider building that specific functionality in another JVM language. Maybe Scala?
You could try doing something like this:
Java: Extending Class At Runtime
At runtime your code would extend the class of the Command to be instantiated and implement the AuthorizedCommand interface. This would make the class an instance of AuthorizedCommand while retaining the original Command class structure.
One thing to watch for, you wouldn't be able to extend any classes with the "final" keyword.
I have a project that is using CQRS and Dependency Injection. The Query side of the system is fine.
For the command side of the system I have chosen to use a queue:
BlockingQueue<Command> commandQueue;
This stores the commands as they are received along with their arguments from multiple threads. The commands all implement a common interface with an execute method:
public interface Command extends Serializable {
void execute();
}
The arguments for the Commands are stored as data in the concrete implementations of the Command interface. The types and potentially number of arguments will vary depending on which command it represents, using this structure means that this detail is all encapsulated away from the command queue logic.
The idea is that the commands are later executed in sequence by a worker thread which calls execute() on each Command in turn without caring about which command it is under the hood.
The commands only require injection once they are taken off the queue ready for execution (this is mostly because I would like to be able to serialize commands, but also because the execution of commands needs different modules to the part of the application that receives and queues them)
My problem is this:
Because the commands need to wait until they are taken off the queue to get their dependencies, I end up passing a lightly wrapped Injector to their 'execute' method so they can create themselves an object graph. This feels more like the Service Locator pattern than Dependency Injection.
public interface Command extends Serializable {
void execute(**ExecutorLocator locator**);
}
Is there something I'm missing or is it inevitable that DI has to look like a service locator at some point in the stack?
It's been a while since I laid my hands on Java code but good architecture and design is not bound to a language.
First: ServiceLocator is an anti-pattern.
Second: Tell, don't ask. If anything build-up the commands from the outside and don't let them ask a locator for their dependencies.
Third: I would create handlers that are registered for the commands and know how to handle the information encapsulated in the commands. Thus you would not need to inject or build-up your commands at all. Setup your handlers and make sure your commands get there.