how to transform interface to abstract by using javassist - aop

I am using javassist library for modify class files.
I want to modify interface to abstract class
for example,
original :
public interface javax.servlet.Servlet {
public void init(ServletConfig config) throws ServletException;
}
modified :
public abstract javax.servlet.Servlet {
public void init(ServletConfig config) throws ServletException {
System.out.println(config.getServletContext().getServerInfo());
callMethod(); // this is implemented original method
}
}
How can i apply this solution like aop(before, after)?

I think the first problem with your approach is that when you try to modify your interface using Javassist you are attempting to redefine an interface that has been already loaded by the class loader.
One option might be to do a bit of classloader tricks: create a new classloader that doesn't have your existing interface loaded (parent is the system classloader) and have Javassist load through that (use aCtClass.toClass() method that takes a ClassLoader argument). However is not really something I would do since to manage properly more than one ClassLoader is not that easy.
There might be a better way to achieve your goal, and creating new classes might be a better design. You could create a new class that implements everything you need and then extends the required interface.
Moreover I suggest you to take also a look at dynamic proxies that could be an option as well. Their biggest advantage is that you don't need any 3rd party libraries to create them.

Related

When I subclass a class using ByteBuddy in certain situations I get IllegalAccessErrors. Why?

(I am a new ByteBuddy user. I'm using ByteBuddy version 1.10.8 and JDK 11 without the module path or any other part of the module system.)
I have a nested class declared like this:
public static class Frob {
protected Frob() {
super();
}
public String sayHello() {
return "Hello!";
}
}
(Its containing class is foo.bar.TestExplorations.)
When I create a dynamic subclass of Frob named foo.bar.Crap like the following, everything works OK as I would expect:
final String className = "foo.bar.Crap";
final DynamicType.Unloaded<?> dynamicTypeUnloaded = new ByteBuddy()
.subclass(Frob.class)
.name(className)
.make();
final Class<?> mySubclass = dynamicTypeUnloaded
.load(this.getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertNotNull(mySubclass);
assertEquals(className, mySubclass.getName());
final Object frobSubclass = mySubclass.newInstance();
assertTrue(frobSubclass instanceof Frob);
But if I change Frob's constructor so that it is package private, I get the following error from the final assertion:
java.lang.IllegalAccessError: class foo.bar.Crap tried to access method 'void foo.bar.TestExplorations$Frob.<init>()' (foo.bar.Crap is in unnamed module of loader net.bytebuddy.dynamic.loading.ByteArrayClassLoader #5e3d57c7; foo.bar.TestExplorations$Frob is in unnamed module of loader 'app')
For some reason, Crap's constructor cannot call super(), even though Crap and Frob are in the same package, and Frob() is defined as package-private.
I have a sense the JDK module system is to blame here, even though I am deliberately (very, very deliberately) not using it. I know the module system does not like split packages, which is what it looks like to me is going on here. Is there a constructor strategy or other mechanism to work around this problem?
In Java, a package is only equal to another package if it has the same name and is loaded by the same class loader (the same as it is with classes). If you are using the WRAPPER strategy, you cannot access package-private members of any super class. Byte Buddy does not forbid the generation as it would be legal to do in javac but you would need to use the INJECTION strategy to do what you want to make sure that classes are loaded by the same class loader. Mind that it uses internal API, therefore, from Java 9, you'd rather use a ForLookup class loading strategy.

Unity IoC static class to access resolved concrete class for S3 image retrieval

I am writing a static class that will allow me to resolve a file name which I am storing on S3.
I want it as a static class so I can globally use it but I want to to be backed by an IStorage interface so I can switch out the concrete class easily. The problem I am having is with static classes not working with Unity - this of course makes sense but I really dont want to start mixing DI code within my static class. I have read about using a delegate wrapper but I am a little confused as to how this could work, as the DI would only be resolving the concrete and therefore where does the static class come in to play? Here is what I have so far
public static class StorageStatic
{
public static string GetFileName(string filename)
{
//This needs to resolve to the correct concrete class, but cannot get the instance of it.
return filename;
}
}

What is the benefit of using a Ninject.Factory over just injecting the IKernel?

According to this article (first paragraph), it is bad practice to inject your IKernel into wherever you need it.
Instead it is proposed to introduce a factory interface that is automatically implementend by Ninject (doing internally the same resolution).
This is an actual code snipped I am working on:
Former implementation:
public class CommandServer
{
[Inject]
public IKernel Kernel { get; set; }
....
public TResponse ExecuteCommand<TRequest, TResponse>(TRequest request)
where TResponse : ResponseBase, new()
{
...
var command = Kernel.Get<ICommand<TRequest, TResponse>>();
...
}
}
Using a factory:
public class CommandServer
{
[Inject]
public ICommandFactory CommandFactory { get; set; }
....
public TResponse ExecuteCommand<TRequest, TResponse>(TRequest request)
where TResponse : ResponseBase, new()
{
...
var command = CommandFactory.CreateCommand<TRequest, TResponse>();
...
}
}
// at binding time:
public interface ICommandFactory
{
ICommand<TRequest, TResponse> CreateCommand<TRequest, TResponse>();
}
Bind<ICommandFactory>().ToFactory();
I am not saying I don't like it (it looks nice and clean) - just not exactly sure why the former is particularly bad and the latter is so much better?
Generally you should not be using the Service Locator pattern. Why you ask? Please see Mark Seeman(comments, too!) and this SO question. Using the IKernel (or somewhat better: only the IResolutionRoot part of it) smells like Service Locator.
Now Mark would suggest that you should apply the Abstract Factory Pattern instead - and he also mentions the Dynamic proxy approach.
I personally think that using ninject auto-generated factories (= dynamic proxy approach) instead is worth the trade off.
You should not use a factory like:
public interface IServiceLocator
{
T Create<T>();
}
because well.. it's service locator ;-)
However, using something like
public interface IResponseHandleFactory
{
IResponseHandle Create(int responseId);
}
is perfectly fine.
Of course you can also do this by using the IResolutionRoot directly - instead of the factory. The code would look like:
IResolutionRoot.Get<IResponseHandle>(
new ConstructorArgument("responseId", theResponseIdValue);
Reasons not to use IResolutionRoot directly
A lot of the IResolutionRoot "methods" are in fact extension methods. That complicates unit-testing a lot (it's basically not a sensible choice if you want to unit test it, at all).
slight worse decoupling from container (=> ease of changing DI containers) than when using a factory interface. The auto-generated factory feature you can also implement as an add on to other containers - if they don't have it already (i've done so personally for Unity and AutoFac). However it requires some know-how about dynamic proxies.
Alternative to factory interfaces: Using Func<> factories. The above example could also be replaced by Func<int, IResponseHandle>(). Quite a lot DI containers support this out of the box / with standard plugins (ninject needs the Factory extension). So you'd be decoupled from the container even more. Disadvantage: harder to unit test and not clearly named parameters.

Avoid adding/extending methods to interface

I have a scenario , where my current interface looks like
public interface IMathematicalOperation
{
void AddInt();
}
After an year i expect the interface to be extended with AddFloat method and also expect 100 users already consuming this interface. When i extend the interface with a new method after an year i don't want these 100 classes to get changed.
So how can i tackle this situation ? Is there any design pattern available already to take care of this situation ?
Note: i understand that i can have a abstract class which implement this interface and make all the methods virtual , so that clients can inherit from this class rather than the interface and override the methods . When i add a new method only the abstract class will be changed and the clients who are interested in the method will override the behavior (minimize the change) .
Is there any other way of achieving the same result (like having a method named Add and based on certain condition it will do Float addition or Integer addition) ?
Edit 1:
The new method gets added to the interface also needs to be called automatically along with the existing methods(like chain of responsibility pattern).
There are at least two possible solution I can think of:
Derive your new interface from your old interface
public interface IMathematicalOperation
{
void AddInt();
}
public interface IFloatingPointMathematicalOperation : IMathematicalOperation
{
void AddFloat();
}
Have simply a parallel interface which contains the new method and have all classes which need the new interface derive from it
I'd suggest the second solution, since I don't understand why you would want an established interface to change.
I encountered a similar issue some time ago and found the best way was not to try and extend an existing interface, but to provide different versions of the interface with each new interface providing extra functionality. Over time I found that was not adding functionality on a regular basis, may once a year, so adding extra interfaces was never really an issue.
So, for example this is your first version of the interface:
public interface IMathematicalOperation
{
void AddInt();
}
This interface would then be implemented on a class like this:
public class MathematicalOperationImpl : IMathematicalOperation
{
public void AddInt()
{
}
}
Then when you need to add new functionality, i.e. create a version 2, you would create another interface with the same name, but with a "2" on the end:
public interface IMathematicalOperation2 : IMathematicalOperation
{
void AddFloat();
}
And the MathematicalOperationImpl would be extended to implement this new interface:
public class MathematicalOperationImpl : IMathematicalOperation, IMathematicalOperation2
{
public void AddInt()
{
}
public void AddFloat()
{
}
}
All of your new/future clients could start using the version 2 interface, but your existing clients would continue to work because they will only know about the first version of the interface.
The options provided are syntactically viable but then, as is obvious, they won't apply to any previous users.
A better option would be to use the Visitor pattern
The pattern is best understood when you think about the details of OO code
this.foo(); // is identical to
foo(this);
Remember that there is always a hidden 'this' parameter passed with every instance call.
What the visitor pattern attempts to do is generalize this behavior using Double dispatch
Let's take this a hair further
public interface MathematicalOperation
{
void addInt();
void accept(MathVisitor v);
}
public interface MathVisitor {
void visit(MathematicalOperation operation);
}
public class SquareVistor implements MathVisitor {
void visit(MathematicalOperation operation) {
operation.setValue(operation.getValue() * 2);
}
}
public abstract class AbstractMathematicalOperation implements MathematicalOperation {
public void accept(MathVisitor f) {
f.visit(this); // we are going to do 'f' on 'this'. Or think this.f();
}
}
public class MyMathOperation extends AbstractMathematicalOperation {
}
someMathOperation.visit(new SquareVisitor()); // is now functionally equivalent to
someMathOperation.square();
The best bet would be for you to roll-out your initial interface with a visitor requirements, then immediately roll-out an abstract subclass that gives this default implementation so it's cooked right in (As the above class is). Then everyone can just extend it. I think you will find this gives you the flexibility you need and leaves you will the ability to work with legacy classes.

Persistence classes in Qt

I'm porting a medium-sized CRUD application from .Net to Qt and I'm looking for a pattern for creating persistence classes. In .Net I usually created abstract persistence class with basic methods (insert, update, delete, select) for example:
public class DAOBase<T>
{
public T GetByPrimaryKey(object primaryKey) {...}
public void DeleteByPrimaryKey(object primaryKey) {...}
public List<T> GetByField(string fieldName, object value) {...}
public void Insert(T dto) {...}
public void Update(T dto) {...}
}
Then, I subclassed it for specific tables/DTOs and added attributes for DB table layout:
[DBTable("note", "note_id", NpgsqlTypes.NpgsqlDbType.Integer)]
[DbField("note_id", NpgsqlTypes.NpgsqlDbType.Integer, "NoteId")]
[DbField("client_id", NpgsqlTypes.NpgsqlDbType.Integer, "ClientId")]
[DbField("title", NpgsqlTypes.NpgsqlDbType.Text, "Title", "")]
[DbField("body", NpgsqlTypes.NpgsqlDbType.Text, "Body", "")]
[DbField("date_added", NpgsqlTypes.NpgsqlDbType.Date, "DateAdded")]
class NoteDAO : DAOBase<NoteDTO>
{
}
Thanks to .Net reflection system I was able to achieve heavy code reuse and easy creation of new ORMs.
The simplest way to do this kind of stuff in Qt seems to be using model classes from QtSql module. Unfortunately, in my case they provide too abstract an interface. I need at least transactions support and control over individual commits which QSqlTableModel doesn't provide.
Could you give me some hints about solving this problem using Qt or point me to some reference materials?
Update:
Based on Harald's clues I've implemented a solution that is quite similar to the .Net classes above. Now I have two classes.
UniversalDAO that inherits QObject and deals with QObject DTOs using metatype system:
class UniversalDAO : public QObject
{
Q_OBJECT
public:
UniversalDAO(QSqlDatabase dataBase, QObject *parent = 0);
virtual ~UniversalDAO();
void insert(const QObject &dto);
void update(const QObject &dto);
void remove(const QObject &dto);
void getByPrimaryKey(QObject &dto, const QVariant &key);
};
And a generic SpecializedDAO that casts data obtained from UniversalDAO to appropriate type:
template<class DTO>
class SpecializedDAO
{
public:
SpecializedDAO(UniversalDAO *universalDao)
virtual ~SpecializedDAO() {}
DTO defaultDto() const { return DTO; }
void insert(DTO dto) { dao->insert(dto); }
void update(DTO dto) { dao->update(dto); }
void remove(DTO dto) { dao->remove(dto); }
DTO getByPrimaryKey(const QVariant &key);
};
Using the above, I declare the concrete DAO class as following:
class ClientDAO : public QObject, public SpecializedDAO<ClientDTO>
{
Q_OBJECT
public:
ClientDAO(UniversalDAO *dao, QObject *parent = 0) :
QObject(parent), SpecializedDAO<ClientDTO>(dao)
{}
};
From within ClientDAO I have to set some database information for UniversalDAO. That's where my implementation gets ugly because I do it like this:
QMap<QString, QString> fieldMapper;
fieldMapper["client_id"] = "clientId";
fieldMapper["name"] = "firstName";
/* ...all column <-> field pairs in here... */
dao->setFieldMapper(fieldMapper);
dao->setTable("client");
dao->setPrimaryKey("client_id");
I do it in constructor so it's not visible at a first glance for someone browsing through the header. In .Net version it was easy to spot and understand.
Do you have some ideas how I could make it better?
As far as I know there is nothing ready made that gives to this facility directly in qt. There are some possible approaches.
Implement the fields as Q_PROPERTY, the are then reflected through the Metaclass system and can be used to implement generic DAO functionality
You could still use the QSqlTableModel but encapsulate writes with transactions, if a transaction fails, refresh the model from the DB. Feasibility depends on the size of the data that you hold in the the model.
We currently use a TableModel/QSqlRecord based approach for reading and writing, there is no ORM mapping done in our system. I have been trying to engineer a more generic approach but the refactoring work that we would have to do to get there is to costly at the moment.
This link http://giorgiosironi.blogspot.com/2009/08/10-orm-patterns-components-of-object.html is not Qt related but a good overview of implementation patterns
If you want an ORM which only depends on Qt and builds upon Qt's Meta-Object System to provide instrospection, you might consider trying QDjango. On top of the basic create/update/delete operations at the model level, it provides a queryset template class (modeled after django's querysets) which allows to build fairly complex lookups. QtScript integration is also underway.
Tegesoft has recently release a new version of its library named CAMP that provide C++ runtime reflexion as you are using in .Net. I think this will allow you to achieve your application like you have done in .Net.
There is also a new open source ORM C++ library : QxOrm. QxOrm is based on QtSql Qt module to communicate with database and boost::serialization to serialize your data with xml and binary format. The web site is in french but quick sample code and tutorial code is in english (a translation is in progress...).
...And one more new Qt ORM: QST: QsT SQL Tools (latest stable version - 0.4.2a release).
QST provides mechanism to generate simple SQL queries: SELECT, INSERT, DELETE, UNPDATE and EXECUTE. Version 0.4 uses T-SQL; new version - 0.5 - will use PostgreSQL by default. You will find, this ORM based on original, unusual conceptions. For example, it integrated with Qt Interview system, so you can setting up view representation (column widths, titles) much easy.
There are example projects for versions 0.3 and 0.4: TradeDB 0.3, TradeDB 0.4. TradeDB 0.4 should be useful to start learning QST.
This seems like an excellent technique. I am, however, having some problems getting my prototype to compile n link....
I've implemented the basics as you describe and call the DAO class to retrieve an instance of one of my DB-resident objects.
Here are the statements calling this these model classes:
_db = <create QSqlDatabase>;
dao = new UniversalDAO (_db);
AddressDAO * aDAO = new AddressDAO (dao);
Address addr = aDAO->getByPrimaryKey(QVariant(1));
In my AddressDAO.cpp, I have:
template<class Address>
Address SpecializedDAO<Address>::getByPrimaryKey(const QVariant &key)
{ }
At link time, I get the following:
undefined reference to
`SpecializedDAO<Address>::getByPrimaryKey(QVariant const&)'
How would I correctly implement the methods in the SpecializedDAO class?
Update:
Stupid me, stupid me, stupid me.... I mostly got this to work. The issues....
My model classes (DTOs) are wrapped in namespaces and I use macros to define and use these namespaces. Plus, I tried to use a good hierarchy for these classes and found that moc has a reeeeal problem with class hierarchies wrapped in namespaces....
I fergot that function definitions of template classes need to be in the header file - can't be in separate compilation units.
qmake doesn't deal with (header file) dependencies very well when crossing library boundaries. I have my model stuff in a shared lib and the 'main()' function (in a separate directory) was trying to read a record from the DB. The 'main()' C file wasn't getting re-compiled when I changed my model class header file...
Here are more details:
In SpecializedDAO.h:
template<class DTO>
DTO SpecializedDAO<DTO>::getByPrimaryKey(const QVariant &key)
throw (FlowException)
{
DTO obj;
dao->getByPrimaryKey(static_cast<QObject &> (obj), key);
return obj;
}
In UniversalDAO.cpp:
void
UniversalDAO::getByPrimaryKey (QObject & dto, const QVariant & key)
{
<retrieve properties from 'dto' n build up QSqlQuery>
<execute QSqlQuery 'SELECT...' to retrieve record>
<call dto.setProperty() on all fields>
}
A current outstanding issue is use of user-defined types for property types in my DTO classes. I'm trying to use std::string vs. QString, but no matter what I tried (Q_DECLARE_METATYPE(std::string), qRegisterMetaType<std::string>(), etc., nothing seemed to work.... had to revert to Qt-based types. bummer....