I'm currently digging into Apache MINA. It's a great framework with lots of capabilities. The hardest part until now was the decoder part. Checking the api documents I understand that there are the following classes that one can extend and implement his own:
DemuxingProtocolDecoder - A composite ProtocolDecoder that demultiplexes incoming IoBuffer decoding requests into an appropriate MessageDecoder.
ObjectSerializationDecoder - A ProtocolDecoder which deserializes Serializable Java objects using IoBuffer.getObject(ClassLoader).
PrefixedStringDecoder - A ProtocolDecoder which decodes a String using a fixed-length length prefix.
All of the above extend the CumulativeProtocolDecoder class - A ProtocolDecoder that cumulates the content of received buffers to a cumulative buffer to help users implement decoders.
Could you please mention with some real world examples what subclass of CumulativeProtocolDecoder you would or did use and why?
Is there an example that doesn't need the decoder to extend the CumulativeProtocolDecoder class and just implement the ProtocolDecoder directly without worrying about fragmentation?
I am using an instance of DemuxingProtocolDecoder class with my application. Under the package org.apache.mina.filter.codec.demux there are some interfaces and classes that you can use to decode your messages. There is an interface called MessageDecoder. Create your own class that implements this interface and MINA will the work. Something like this,
public class MyDecoder implements MessageDecoder {
public MessageDecoderResult decode(IoSession session, IoBuffer buffer, ProtocolDecoderOutput decoderOutput) throws Exception {
/* Your
decode
mechanism */
decoderOutput.write(message); // don't forget to write your decoded message object at some point.
return MessageDecoder.OK; //or something else that matches your needs.
}
}
Related
I am trying to develop a simple SMTPclient for testing purposes using the SubethaSmtp client package. i want to use the SMTPClient class instead of the SmartClient class for more control but i have not been able to figure out how to write mail data using SMTPClient, the only OutputStream exposed to public or external subclasses is the one for sending commands, the ones for sending data (after sending the DATA command) is exposed only to classes in the same package (SmartClient).
am i missing something here? i would like to know how a direct subclass of SMARTClient can written to work around this problem.
Looks like you are correct, you cannot simply extend the SMTPClient and get access similar to the one that SmartClient has, being a same-package class.
At this point you can either:
1) Fork your own version of the app from https://github.com/voodoodyne/subethasmtp and do whatever the hell you like with it, or
2) Go all the way and implement your own version of SMTPClient, as the package protected SMTPClient.dotTerminatedOutput;, used by SmartClient.dataWrite() actually is just instantiated like so
...
this.rawOutput = this.socket.getOutputStream();
this.dotTerminatedOutput = new DotTerminatedOutputStream(this.rawOutput);
...
I am working on a web application which is based on spring MVC. We have various screens for adding different domain components(eg. Account details, Employee details etc). I need to implement an upload feature for each of these domain components i.e. to upload Account, upload employee details etc which will be provided in a csv file (open the file, parse its contents, validate and then persist).
My question is, which design pattern should i consider to implement such a requirement so that upload (open the file, parse its contents, validate and then persist) feature becomes generic. I was thinking about using the template design pattern. Template Pattern
Any suggestions,pointers,links would be highly appreciated.
I am not going to answer your question. That said, let me answer your question! ;-)
I think that design patterns should not be a concern in this stage of development. In spite of their greatness (and I use them all the time), they should not be your primary concern.
My suggestion is for you to implement the first upload feature, then the second and then watching them for what they have that is equal and create a "mother" class. Whenever you come to a third class, repeat the process of generalization. The generic class will come naturally in this process.
Sometimes, I believe that people tend to over engineer and over plan. I am in good company: http://www.joelonsoftware.com/items/2009/09/23.html. Obviouslly, I am not advocating for no design software - that never works well. Nevertheless, looking for similarities after some stuff has been implemented and refactoring them may achieve better results (have you already read http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672/ref=sr_1_1?ie=UTF8&qid=1337348138&sr=8-1? It is old but stiil great!).
A strategy pattern my be useful here for the uploader. The Uploader class would be a sort of container/manager class that would simply contain a parsing attribute and a persistance attribute. Both of these attributes would be defined as an abstract base class and would have multiple implementations. Even though you say it will always be csv and oracle, this approach would be future-proof and would also separate the parsing/verifying from the persistence code.
Here's an example:
class Uploader
{
private:
Parser parser_;
Persistence persistence_;
void upload() {
parser_.read();
parser_.parse();
parser_.validate();
persistence_.persist(parser_.getData());
}
public:
void setParser(Parser parser) {parser_ = parser;}
void setPersister(Persistence persistence) {persistence_ = persistence;}
};
Class Parser
{
abstract void read();
abstract void parse();
abstract void validate();
abstract String getData();
};
class Persistence
{
abstract persist(String data);
};
class CsvParser : public Parser
{
// implement everything here
};
// more Parser implementations as needed
class DbPersistence : public Persistence
{
// implement everything here
};
class NwPersistence : public Persistence
{
// implement everything here
};
// more Persistence implementations as needed
You could use an Abstract Factory pattern.
Have an upload interface and then implement it for each of the domain objects and construct it in the factory based on the class passed in.
E.g.
Uploader uploader = UploadFactory.getInstance(Employee.class);
Currently our application uses GWT-RPC for most client-server communication. Where this breaks down is when we need to auto generate images. We generate images based on dozens of parameters so what we do is build large complex urls and via a get request retrieve the dynamically built image.
If we could find a way to serialize Java objects in gwt client code and deserialize it on the server side we could make our urls much easier to work with. Instead of
http://host/page?param1=a¶m2=b¶m3=c....
we could have
http://host/page?object=?JSON/XML/Something Magicical
and on the server just have
new MagicDeserializer.(request.getParameter("object"),AwesomeClass.class);
I do not care what the intermediate format is json/xml/whatever I just really want to be able stop keeping track of manually marshalling/unmarshalling parameters in my gwt client code as well as servlets.
Use AutoBean Framework. What you need is simple and is all here http://code.google.com/p/google-web-toolkit/wiki/AutoBean
I've seen the most success and least amount of code using this library:
https://code.google.com/p/gwtprojsonserializer/
Along with the standard toString() you should have for all Object classes, I also have what's called a toJsonString() inside of each class I want "JSONable". Note, each class must extend JsonSerializable, which comes with the library:
public String toJsonString()
{
Serializer serializer = (Serializer) GWT.create(Serializer.class);
return serializer.serializeToJson(this).toString();
}
To turn the JSON string back into an object, I put a static method inside of the same class, that recreates the class itself:
public static ClassName recreateClassViaJson(String json)
{
Serializer serializer = (Serializer) GWT.create(Serializer.class);
return (ClassName) serializer.deSerialize(json, "full.package.name.ClassName");
}
Very simple!
I'm trying to create a system that will, on every RMI call,
1) gather some data about the current local system state (let's say the system time)
2) serialize it and transparently add it to the data sent over the wire with the call (ie, without changing the signature of the stub method being called)
3) deserialize it on the other side and take some action (let's say logging it to a file)
4) do the same thing in reverse when the method returns
I've was trying at first to do this with AspectJ, adding a pointcut at java.rmi.server.RemoteRef's invoke method that would allow me to add the metadata to the params Object array, but I've now discovered that AspectJ can't advise already-compiled code, which makes a lot of sense.
So, what's the right way to do this?
Well, I am not sure if I am getting enough context from what you are saying, but I think you could write the metadata upon serialization/deserialization of objects passed to and received from the server.
For instance, let's say you server is returning Jedi instances. And Jedi is a Serializable class. Then you could use the writeObject() and readObject() methods (as explained in the Java Serialization Specification) to write whatever special additional information that you may need at the client/server side.
For instance:
public class Jedi {
....
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.writeObject(new Date());
stream.defaultWriteObject();
}
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
Date sysDate = (Date) stream.readObject();
System.out.println(sysDate);
stream.defaultReadObject();
}
}
The only problem as that you would be forced to do this for every serializable object you interchange with your server.
You could also investigate RMI/JERI in the Jini 2 project. JERI stands for Java Extensible Remote Invocation protocol, i.e. you can customize it in numerous ways.
In the context of an Eclipse RCP application I decided to use OSGi services to provide "Interfaces" out of a plugin (i.e a bundle).
In one of my plugin I have the following Parser interface:
public interface Parser {
public void start(File file);
public boolean hasNext();
public Object next();
}
Consumer plugins will use this interface to parse files. Because several parsing can be done in the same time and because an implementation of this interface will need several "state" private field each consumer of this service must use a dedicated service instance.
In this case, the default solution provided by manu OSGi tutorials consisting in registering ONE service instance in the start method of the parser bundle doesn't work. What is the best solution to handle such a solution ?
I can create a ParserFactory service with one unique method:
public Parser create(File file);
??
Any comment is welcome,
As you're suggesting, I would change your service interface to be a provider of Parsers.
And your Parser is just an Iterator, so maybe something like
public interface ParserFactory<T> {
/** Iterating on the returned object
* provides Ts parsed from the InputStream.
*
* #param input must be closed by the returned object
* when done iterating.
*/
Iterable<T> createParser(InputStream input);
}
Using an InputStream or Reader also makes it more flexible that requiring a File.
Have a look at the OSGi ServiceFactory; this allows you to instantiate services for different requesting bundles. You can read more about it in section 5.6 of the core specification.