My requirement is that the user will see localized messages at the end of the process. If the process failed, there will be at least one "external" message of type error. If the process was successfully executed, the user might see multiple "external" information messages.
Additionally, all messages (including internal) shall be logged by the application.
Now here comes the tricky part. Assume the following callstack:
controller.uploadImageHandler
imageService.createImageContainer
galleryService.loadForImage
galleryService.validateGalleryAttributes
Now validateGalleryAttributes will validate 3 attributes. 2 aren't matching, so the messages Attribute A must be X and Attribute B must not be empty of type External are generated and logged to the application log. The calls before added multiple information messages.
Now I need have to
abort processing
bubble the Messages up
Is the right approach to pass along a Message Collection (or add a collection to the logger) into every method, throw an Exception upon failure (even simple ones such as invalid attributes), extract the messages at the controller level and return them to the user? It's not enough to add them to the exception class, since info messages must also be possible and multiple methods might produce just messages.
But honestly it seems a bit weird to have a collection that is inspected upon success and exception. Is there a better language construct?
Theres two alternative solutions that I could come up with.
If you are into monads at all you could move away from using exceptions to a custom LoggingEither<L, R> or LoggingResult<S, E> return type. They would carry the result/exception as well as all accumulated messages so far. You would just have to make sure to merge the messages of all methods you call into the object you return in the current method. For an idea of how these monad types could be implemented take a look at vavr.
If everything happens in the same Thread you could consider using ThreadLocal to keep track of all the log messages. This eliminates the need of passing a collection down the stacktrace. You will still need to take care of bundling messages and resetting the ThreadLocal, though.
Related
I have read through the Javadocs for the reactor.core.publisher.Mono class From project reactor However I still don't understand what's the point of having the Mono.never() method.
What are some example use cases where one would use Mono.never()?
It is very often used in tests (typically to assert timeout behavior), but can also have production usage: some operators take a control Publisher as parameter in various situations where they need an asynchronous external signal to tell them to trigger some behavior. If in some cases you don't want said behavior to trigger, user never().
For instance, windowWhen takes such parameter both for opening and closing windows (the later generated by a Function). Conditionally returning a Mono.never() you could have a window that never closes.
I am designing a Swing window for managing the information about a NonPlayerCharacter entity. The design is intended to be easily extensible. The main body of the editor form is contained inside a tabbed pane, so that future extension modules can add tabs to extend the editor.
The tabbed pane can be populated by tabs that implement the NPCEditorTab interface. Part of the "Saving" process involves a loop that cycles through the tabs calling the verifyFields() method on each, ensuring that all fields are properly completed (I supposed to keep with convention I should rename this to validateFields()). If the validation of all tabs is successful, another loop calls the saveNPC() method for each tab, instructing them to write their data to the NPC object.
My question is: What is the best method for tracking the validation of each tab so that the reasons for a failed validation can be reported to the user?
I have two options:
1) Have the method throw a ValidationException.
This ValidationException would contain information regarding the source tab and which form fields were incomplete and why, allowing the editor to report this to the user as a single message. I would probably collect exceptions as they occur in a collection and complete all the validations before reporting the results from all the tabs at once (to prevent a case of the user receiving an Error from Tab 2, fixing that, then oh, you also have an error in tab 4, etc).
Reading on here and elsewhere suggestions that using exceptions for flow control is bad design, which is why I'm hesitant to use this option.
2) Have the method return a ValidationResult object.
These ValidationResult objects would be added to a collection after each iteration and examined. They would contain a boolean flag (isValidated()), a source String identifying the source tab, as well as a List of Strings describing reasons for validation failure.
In either case validation results would be reported to the user in a single dialogue.
I don't personally see a problem with the first option, as to me (a self-taught Java enthusiast) it seems to the least performance impacting (an object is only generated in the event of a failure, as opposed to every time no matter what as with the second option).
I have no experience with developing a custom API (I sort of enjoy feeling my way along and finding ways to handle problems on my own), but I am attempting to design this program to be extensible so that I can easily add functionality later without massive modifications to the existing code (I ran into this problem on my first iteration of this project, each new feature made the base code more and more convoluted until it became unmanageable).
That is the reason I am handling form validation this way, I am just wary of including validation reporting in the individual tabs because I don't want the user to receive a unique notice for each individual tab. However, if you think the best method is to do just that (IE when a tab's validation fails, it notifies the user itself via JOptionPane and then returns false which terminates the validation check), let me know.
Addendum
Upon outside advice, I have decided to scrap the entire multi-tab validation scheme and instead validate on individual form elements by capturing lost-focus events and forcing the user to correct invalid input immediately after it is entered.
I would prefer 2) option. You can see for example SpringMVC validation logic.
Each field of form could be annotated with necessary validation e.g. #Email, #NotEmpty etc.
On validate there is a collection of errors (could be empty if all the fields are valid). Then each filed could be marked somehow with error message particular for the field (empty if it's valid).
On check there could be a message about errors. On clising the message would be good to point (e.g. set focus) on the first invalid control.
I have a multithread server, waiting for socket connections.
The first exchange of message is always of the same type, the clients sends an object with the authentication details(userid/pwd), the server checks it and reply to the server if the authentication has been passed or not.
After this first exchange of messages, the client will send some requests, corresponding to various tasks the server is able to execute.
How do i model those eterogeneous requests? In particular my question regards the type of object sent between client and server with InputObjecStream/OutputObjectStream
I had 2 ideas:
Using a "generic message" object, with 2 attributes: a task identifier and an HashMap without generics, able to carry various type of parameters requested for executing the task.
An object for every type of task, this solution is "cleaner", but I don't know how to make the server understand the type of the message received, I thought about a series of object casting of the received message from the client to every possible "specific task message", ignoring the many CastException. It sounds just bad, is there any way to avoid this?
Why not combine the two ideas
Start with a common level interface that the server can cast to determine what it should do or now to react.
As the object is passed off to the handler responsible for handling te request can further cast the object (based on a deeper level of interface implementation)
IMHO
The first approach is very generic but will be hard to maintain. After a while you'll notice that you no longer remember what kind of objects should be in this generic map. You'll have to keep the dictionary in sync.
The second approach is much better. Essentially you receive an abstract Request object with various subclasses. The base class can hold some general information. Normally you would use polymorphism and implement the action in each subclass, overriding abstract method from Request class. But you can't because request object would have to hold server-side logic.
The best you can do here is visitor design pattern. With it, for the price of slightly obscuring your code, you'll get very generic and safe design. instanceof tends to be ugly after some time.
What you could do is use XML messages for the communication. You could prepend in the first bytes an indication for which XML object the message should be mapped and on reception of the message, just check these bytes find the indicator, and use the rest bytesequence to marshal the bytes to XML object (using JAXB or SimpleXML or DOM or anyother xml parser) XML is very verbose and you could use it here to encapsulate your messages.
How would you suggest going about implementing the following scenario. I have a few thoughts, but none that satisfies my problem in totality, so I would like to get your input.
I am building a type of work-flow application. The user creates a pipeline of activities that then needs to be executed. The problem I face is this. Each "widget" in the pipeline must define what it can accept as input, and what it will produce as output. It can receive any number of input "streams" and also produce multiple "streams" of output. Now the problem occurs. These need to by dynamic. For instance, someone should be able to write a plugin for the application where he defines his own widget, with inputs and outputs. But other widgets need to be able to connect to it, so that they can send their output to the new one, or receive input from it.
How should one go about firstly exposing the list of acceptable inputs and outputs, and secondly, how can I calculate which method to call on the widget. For example if I want to send output from my widget to the new one, I need to be able to calculate if there is an acceptable receiving method (in which case there could be more than one), and secondly, I need to know the method to call to give the data to.
I have had a look at closure, delegates etc, which seem to be able to do what I need. Just thought I would get some more input first.
Thanks.
I would suggest that you enforce that all your components implement one or more interfaces allowing other components and the framework to use those interfaces to interrogate the component on what it can send and what it can receive.
This will make your code more robust, and require less magic to work.
Have a look at message-driven-architectures and Mule ESB.
I have a layered application in Java which has a multi thread data access layer which is invoked from different points. A single call to this layer is likely to spawn several threads to parallelize requests to the DB.
What I'm looking for is a logging tool that would allow me to define "activities" that are composed by various threads. Therefore, the same method in the data access layer should log different outputs depending on its caller. The ability to group different outputs to summarize the total cost of an operation is also important.
Although the application is in Java, language is not a restriction; what I need are the design guidelines so to eventually implement it. We are currently using log4j, but can't get this behaviour from it.
You should also have a look at the nested diagnostic context feature of log4j. Pushing different contexts to the logger for different callers might do the trick for you.
You should be able to pass a logger around, so you create a logger based on some "common" for the task data - i.e. username, etc. Then, pass this logger as parameter to all methods you need. That way, you'll be able to set different filters and/or rules in your log4j config file. Or to scrape the output file based on the logger name.
EDIT: Also check MDC and NDC classes in log4j. You can add there context data.
In log4j you can log the thread name with the "%t" pattern. See log4j Pattern Layout.
In one of my (web) applications, i use a ThreadLocal logger that captures logging information into a StringBuilder. The logger object is initialized in the HttpServlet#service method, if a trace parameter is set (if it is not set, there is a very fast null-logger). The resulting output is either dumped as a HTML comment into the requesting page, or written to a log file in one segment.
In Java5 (and later) you can call
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
Inspect the stack trace to whatever depth you want and log accordingly.
In Java 1.4 you can get the same info with
StackTraceElement[] stackTrace = new Exception().getStackTrace();
You want to associate logger objects with threads I think. A ThreadLocal variable holding a log4j logger instance for each thread might help:
http://java.sun.com/javase/6/docs/api/java/lang/ThreadLocal.html
You will need to pass some structure to the data access layer that identifies the current "activity". You might already have an "Activity"-class that makes sense, you might use a Logger-instance as Sunny suggested or you might use a third structure to keep track of the activity-context.
In any case, since your "activity" is processed across multiple threads you cannot use thread-local-storage for keeping track of the current "activity", like most of the other current answers suggest. You will need to pass it around explicitly.
I would suggest making a small facade on top of log4j that expands the interface with methods like
void debug(Activity activity, String message);
and passing the activity-context into this from the data access layer.
You will need to make some modification to the data access layer to allow you to pass the current activity to it, but how best to do that depends strongly on the current interface.
If you use the Workspace-pattern, you might just need to add a setActivity() method on the Workspace-class, but other interface-pattern might require you to add an Activity parameter to all methods.
If you for some reason is unable or unwilling to change the data access layer, you might of course store the activity-context in thread-local-storage before invoking the data access layer and retrieve it just before spawning the sub-threads or enqueing the jobs in the data access layer. That is a workable solution, but is it a bit dangerous to pass information around in that way.
You can use MDC or NDC for your scenario, NDC works on principle of stack while MDC works on Map, here is official documentation for both
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/MDC.html
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/NDC.html