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.
Related
I've inherited a Struts2 project which needs some functionality addition. When I ran into de code to guess how the previous guy did things, I found out that if he wants a class to instantiate only once when the Tomcat server starts (because it has to read heavy loads of data from disk, but only once to get its config, for instance), he did this in the following way:
public class ExampleClass {
public ExampleClass(){//Read files and stuff to initialize}
public Object method(Object[] args){//The job to do}
}
And then, in the struts action which uses it he instantiates it this way:
public class SomeAction extends ActionSupport {
ExampleClass example = new ExampleClass()
public String execute() {
//Do stuff every time the action is called
Object result = example.method(args);
// Do stuff with results
}
}
I know from servlet times that this does the trick, however, I feel like the guy who handled this before was as inexperienced in Struts2 as I am, so here comes my question:
Is this the proper way to do so according to style recommendations and best practices? Does struts2 provide a more controlled way to do so?
I found some answers related to simple parameters here, but I'm not sure if this is the proper way for objects like those? What would happen if ExampleClass instance is really heavy? I don't want them to be copied around:
How to set a value in application scope in struts2?
Some background about ExampleClass: When the constructor is called, it reads large sets of files and extracts it's configurations from them, creating complex internal representations.
When method() is called, it analyzes it's parameters using the rules, and outputs results to the user. This process usually takes seconds, and doesn't modify the previously initialized rule values.
This is running in Tomcat 7, however, I'm planning to upgrade to Tomcat 8.5 when everything is in place. I'd like to know if there are known issues about this regarding to this setup aswell (there are no other incompatibilities in the code).
BTW: He's not checking if ExampleClass is broken or anything like that, this definetly looks like a recipe to disaster xD. In fact, If I remove the source files, it is still trying to execute the method()... Poor soul...
Ideally, I need a way to instantiate all my application-level objects on start-up (they're the application itself, the rest is just a mere interface) in a way that if they fail Struts2 will tell Tomcat not to start that war, with the corresponding error logging and so on.
If Struts2 doesn't support this, which is the commonly accepted work-around? Maybe some Interceptor to check the object status and return to a error page if it hasn't been correctly instantiated? Execute a partial stop of tomcat from within?
All the objects of this project are thread safe (the only write operation inside them is performed on initialization), but I'd like to know best practices for Struts2 when objects are not so simple. What happens if a user can actually break one? (I know I should by any means avoid that, and I do, but mistakes happen, so I need a secure way to get through them, and get properly alerted, and of course I need a way to reinstantiate it safelly or to stop the whole service).
Right now, I can manually execute something like:
public class SomeAction extends ActionSupport {
ExampleClass example = new ExampleClass();
private boolean otherIsBuildingExample = false;
public String execute() {
if(otherIsBuildingExample) return '500 error';
if(example==null || example.isBroken()){
otherIsBuildingExample = true;
example = new ExampleClass();
otherIsBuildingExample = false;
}
Object result = example.method(args);
// Do stuff with results
}
}
Indeed, this would be cleaner with Interceptors, or so, however, this sounds like a pain in the *** for concurrency, specially taking into consideration thay example takes several seconds to start, and that more requests can come, so more concerns to take into consideration, like: what if two people call if(otherIsBuildingExample) and the second one gets the value before the first one performs otherIsBuildingExample=true? Nothing good... If the class is simple enough, both will instantiate and the slower one will prevail, but if one instantiation blocks the other's resources... well, more problems.
The only clean solution I can think of is to make ExampleClass robust enough so you can repare it using its own methods (not reinstantiating) and make those thread safe in the common way (if 10 people try to repair it, only one will proceed, while the others are just waiting for the first to end to continue, for instance).
Or maybe everytime you call execute() you get a copy of example, so no worries at all about this?
I'm digging into struts documentation
Thanks in advance.
I have a some functionality implemented to store documents inside a data base.
Now, I want to access the functionality in my module but not directly.
As I have the FileInputStream with me and the functionality implemented accepts JSON string.
So, which design pattern could be used to bridge the gap in input parameters?
I know Adapter is one of the answers but can anyone suggest anything else?
Below is the sample of the functionality.
public interface DocumentService {
public String create(String jsonRequest);
public String search(String jsonRequest);
public String update(String jsonRequest);
public String fetch(String jsonRequest);
}
To elucidate my comments:
Trying to wedge every bit of functionality into an explicit "pattern" isn't a productive use of your time.
Even if it is, trying to find the perfect "name" for what you actually come up with isn't.
You need a helper class that converts an FIS into JSON, and that's about it.
You could compose a service that uses that helper and your existing class, or...
Compose your existing class into the FIS => JSON converter, or...
Modify your data flow so that you pass the data through a filter that JSONifies it, or...
In other words, (a) the "best" answer depends on your very specific situation, and (b) it doesn't matter what it's called. Do something, put it somewhere half-way reasonable, and if it ends up not being exactly right, iterate until it is. Don't waste time trying to name the "pattern".
It's like throws and joint locks: don't look for them, find them. The patterns are hidden in your application, surface them and implement.
Just make a private converting method
String toJSON(FileInputStream fs) {
...
}
If you happen to need that method in multiple locations move it into a utility class.
If that single method is not flexible enough for every situation you need it in right now then you should consider writing an adapter class.
The desire to design a perfect, flawless architecture for every functionality is natural in many programmers. It poses the risk of paralyzing the actual objective, which is to deliver a working product.
The important thing about good design is not that it fulfills every possible use case that may arise in the future, but that it is easy to understand and easy to change should that use case actually arrive.
Looks like Adapter is a good choice. I will move forward.
Why don't you use the DAO pattern?
Pass the input stream to the DAO object and make it convert it from the file input stream to JSON and call the create methods.
http://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm
Well, I saw there were some questions and answers about this, but they didn't really satisfy me.
Let's say for example, I have programmed a console. It's a nice JFrame with an output and an input txtField/Area. But this console should not only be used for output, but also to run commands.
Because I would need this console very often and I don't want to change the code of the console I programmed it this way:
The console has one method to register commands.
console.registerCommand(String command, String methodToInvoke, Object invokeObject);
With this method I'm able to use this console everywhere without the need of changing or inharitance.
Whenever the String command is written the console knows it's a registered keyword and executes the method via reflection.
Would this be a good or bad practice? On code styling and in performance! And what could I do better?
I also found it quite neat to use reflections this way to add ActionListeners to MenuItems in a TrayIcon.
Edit
To the Answer below:
Ok with commands i would accept this is a way to do. But in the Tray example I wrote a TrayHelper Class which creates the TrayIcon. There I want to add MenuItems and their ActionListeners but without creating every Object myself and add them to the Tray. So I wrote Methods like this:
public void addMenuItem(String label, String methodToInvoke, String invokeObject);
This method not only executes the method when the MenuItem is clicked, but also creates the MenuItem first, adds an ActionListener to it which invokes the Method, and adds it to the TrayIcon.
So in order to use this TrayHelper I can now just write:
th.addMenuItem("Exit","exitMethod",this);//executes the exitMethod of
//this class after Menuitem Exit
//was clicked
I don't really see how i could do this without reflection other than to write all the Objects myself again and adding them to the Tray. Or I'm blind :)
Edit 2
Ok, I was blind. I just didn't realize how to do this without reflection, but it is so simple.
Especially with the Command pattern.
Because of the anonymous classes I could do it that way, and I really like the way to write code this way (I always did it with ActionListeners)
th.addMenuItem("Test",new Command(){
public void execute(){
//do stuff
}
});
Thank you :)
There is a better way to do this. This helps to hide the action done inside a command object. As you have to change the command, you don't have to mess with your other code.
Further, you can have a lot of different commands and they can be related by inheritance or aggregation or be injected into each other as needed AND NOBODY ELSE HAS TO KNOW.
First you have an interface:
public interface Command {
void execute();
}
Then you have your code take one of these:
console.registerCommand(Command command);
Then you write various classes that implement the interface and do something:
public class OneCommand implements Command {
public void execute() {
theObject.theMethod(theCommand); // calls what you would have with reflection
}
}
This is the standard GOF Command Pattern and you can read more about it here: LINK TO WIKIPEDIA
Note that this pattern, along with the other GOF patterns, were published in a book in 1994. The authors collected these best practices over many software projects. That book is in its 40th printing (according to Wikipedia).
All this suggests that lots of people have found lots of reasons to use these over many pieces of softwear, over many years and in many programming languages and systems.
It doesn't mean you need to always use them but use of a tried and tested pattern will help avoid unseen pitfalls.
Where should my user interface located in a simple CRUD application (with Java).
In my application I have the main class as well as another class which handles all the things which have something to do with the database e.g. getting information from it or adding new info to it.
Is it wiser to keep the UI-elements in the main class and leave the database class take the user input forward e.g. add a new element into database class, like this:
public static void main(String[] args) {
Scanner scan = new Scanner(system.in);
System.out.println("Give me your name:");
String name = scan.nextLine();
DatabaseHandler db = new DatabaseHandler();
db.addNameToDatabase(name);
}
Or should the input prompt exist inside the DatabaseHandler, so in the main-class only the method call is shown, like this:
public static void main(String[] args) {
DatabaseHandler db = new DatabaseHandler();
db.addNameToDatabase(); //user interface now inside addNameToDatabase method
}
It really depends on the size of your program. If your program is small and easy to read in one file then let it be so. As the program gets bigger then it becomes necessary for clarity to break it out. (If it is really small than a straight procedural way of coding might be the best within one class.)
In the case you break it out then the main class should be a driver for both the UI and data portions, which should be in different modules. You might want to look at different patterns like MVC or MVP on how to split it up.
As you can see there is no one way fits all. Large programs that are broken up into components/modules/packages are harder to get your arms around because of the wiring, but make it easier for a team to work on.
Always during development, remember - high cohesion and low coupling. For your particular question, think this way - in either approach, are you having high cohesion? No. Why should the database class handle user input? And why the main method should handle user input? No, both your ways are,well ideally, wrong.
But we seldom come across ideal situations. Your IO should be handled by another class and your database should be handled by another class,so should your UI. And inside these classes as well, each method should have a specific task. Use getters and setters,for instance, in your IO class,to get and set variables. Each method doing what it should do ensures high cohesion. And in this way, you end up ensuring low coupling as well,because your modules won't be interdependent. You might think - oh well, I can write all this in just one class and get it over with, but remember, this approach has a lot of advantage. In situations where the maintenance of your code has to be done by someone else, they would know by the names of classes and methods to know where to look for the issues. In situations where you have to look at your own code after ages, you wouldn't even recognize one word if you aren't organized in this manner.
Remember - high cohesion and low coupling FTW!
Ideally - your main should just be a starting point to your program, and nothing else.
I have a question on the best way of exposing an asynchronous remote interface.
The conditions are as follows:
The protocol is asynchronous
A third party can modify the data at any time
The command round-trip can be significant
The model should be well suited for UI interaction
The protocol supports queries over certain objects, and so must the model
As a means of improving my lacking skills in this area (and brush up my Java in general), I have started a project to create an Eclipse-based front-end for xmms2 (described below).
So, the question is; how should I expose the remote interface as a neat data model (In this case, track management and event handling)?
I welcome anything from generic discussions to pattern name-dropping or concrete examples and patches :)
My primary goal here is learning about this class of problems in general. If my project can gain from it, fine, but I present it strictly to have something to start a discussion around.
I've implemented a protocol abstraction which I call 'client' (for legacy reasons) which allows me to access most exposed features using method calls which I am happy with even if it's far from perfect.
The features provided by the xmms2 daemon are things like track searching, meta-data retrieval and manipulation, change playback state, load playlists and so on and so forth.
I'm in the middle of updating to the latest stable release of xmms2, and I figured I might as well fix some of the glaring weaknesses of my current implementation.
My plan is to build a better abstraction on top of the protocol interface, one that allows a more natural interaction with the daemon. The current 'model' implementation is hard to use and is frankly quite ugly (not to mention the UI-code which is truly horrible atm).
Today I have the Tracks interface which I can use to get instances of Track classes based on their id. Searching is performed through the Collections interface (unfortunate namespace clash) which I'd rather move to Tracks, I think.
Any data can be modified by a third party at any time, and this should be properly reflected in the model and change-notifications distributed
These interfaces are exposed when connecting, by returning an object hierarchy that looks like this:
Connection
Playback getPlayback()
Play, pause, jump, current track etc
Expose playback state changes
Tracks getTracks()
Track getTrack(id) etc
Expose track updates
Collections getCollection()
Load and manipulate playlists or named collections
Query media library
Expose collection updates
For the asynchronous bit, I would suggest checking into java.util.concurrent, and especially the Future<T> interface. The future interface is used to represent objects which are not ready yet, but are being created in a separate thread. You say that objects can be modified at any time by a third party, but I would still suggest you use immutable return objects here, and instead have a separate thread/event log you can subscribe to to get noticed when objects expire. I have little programming with UIs, but I believe using Futures for asynchronous calls would let you have a responsive GUI, rather than one that was waiting for a server reply.
For the queries I would suggest using method chaining to build the query object, and each object returned by method chaining should be Iterable. Similar to how Djangos model is. Say you have QuerySet which implements Iterable<Song>. You can then call allSongs() which would return a result iterating over all Songs. Or allSongs().artist("Beatles"), and you would have an iterable over all Betles songs. Or even allSongs().artist("Beatles").years(1965,1967) and so on.
Hope this helps as a starting place.
Iterable only has the method Iterator get() or somesuch. So no need to build any query or execute any code until you actually start iterating. It does make the execute in your example redundant. However, the thread will be locked until the first result is available, so you might consider using an Executor to run the code for the query in a separate thread.
#Staale
It is certainly possibly, but as you note, that would make it blocking (at home for something like 10 seconds due to sleeping disks), meaning I can't use it to update the UI directly.
I could use the iterator to create a copy of the result in a separate thread and then send that to the UI, but while the iterator solution by itself is rather elegant, it won't fit in very well. In the end, something implementing IStructuredContentProvider needs to return an array of all the objects in order to display it in a TableViewer, so if I can get away with getting something like that out of a callback... :)
I'll give it some more thought. I might just be able to work out something. It does give the code a nice look.
#Staale: Thanks a bunch!
Using Future for the async operations is interesting. The only drawback being that it is doesn't provide callbacks. But then again, I tried that approach, and look where that got me :)
I'm currently solving a similar problem using a worker thread and a blocking queue for dispatching the incoming command replies, but that approach doesn't translate very well.
The remote objects can be modified, but since I do use threads, I try to keep the objects immutable. My current hypothesis is that I will send notification events on track updates on the form
somehandlername(int changes, Track old_track, Track new_track)
or similar, but then I might end up with several versions of the same track.
I'll definitely look into Djangos method chaining. I've been looking at some similar constructs but haven't been able to come up with a good variant. Returning something iterable is interesting, but the query could take some time to complete, and I wouldn't want to actually execute the query before it's completely constructed.
Perhaps something like
Tracks.allSongs().artist("Beatles").years(1965,1967).execute()
returning a Future might work...
My conclusions so far;
I am torn on whether to use getters for the Track objects or just expose the members since the object is immutable.
class Track {
public final String album;
public final String artist;
public final String title;
public final String genre;
public final String comment;
public final String cover_id;
public final long duration;
public final long bitrate;
public final long samplerate;
public final long id;
public final Date date;
/* Some more stuff here */
}
Anybody who wants to know when something happened to a track in the library would implement this...
interface TrackUpdateListener {
void trackUpdate(Track oldTrack, Track newTrack);
}
This is how querys are built. Chain calls to your hearts content. the jury is still out on the get() though. There are some details missing, such as how I should handle wildcards and more advanced queries with disjunctions. I might just need some completion callback functionality, perhaps similar to the Asynchronous Completion Token, but we'll see about that. Perhaps that will happen in an additional layer.
interface TrackQuery extends Iterable<Track> {
TrackQuery years(int from, int to);
TrackQuery artist(String name);
TrackQuery album(String name);
TrackQuery id(long id);
TrackQuery ids(long id[]);
Future<Track[]> get();
}
Some examples:
tracks.allTracks();
tracks.allTracks().artist("Front 242").album("Tyranny (For You)");
The tracks interface is mostly just the glue between the connection and the individual tracks. It will be the one implementing or managing meta-data caching, if any (as today, but I think I'll just remove it during the refactoring and see if I actually need it). Also, this provides medialib track updates as it would just be too much work to implement it by track.
interface Tracks {
TrackQuery allTracks();
void addUpdateListener(TrackUpdateListener listener);
void removeUpdateListener(TrackUpdateListener listener);
}