AspectJ: How to pick the execution of non-annotated methods of subclasses of a given class? - aspectj

I'd like to intercept the execution of non-annotated methods of any subclass of a given class.
For instance, say I have class Base:
public class Base {
public void baseMethod() { //shouldn't be intercepted
// do whatever...
}
}
And, eventually, someone extends Base. Whatever is the new class name, its methods with some annotation #LeaveItAlone should not be intercepted. All the other methods of the subclass should.
public class Sub extends Base {
public void interceptedMethod1() {
// ...
}
public void interceptedMethod2() {
// ...
}
#LeaveItAlone
public void NOTinterceptedMethod1() {
// ...
}
#LeaveItAlone
public void NOTinterceptedMethod2() {
// ...
}
I imagine something like:
pointcut sub_nonannotated() : !execution(#LeaveItAlone * Base+.*(..));
But I'm certain the above is wrong.
Side question: how do I intercept specifically the constructor of the subclass?

Actually I just tried it and you apparently have it almost correct. This is what worked for me:
package com.snaphop.ats.util;
public aspect Blah {
pointcut sub_nonannotated() : !execution(#LeaveItAlone * Base+.*(..));
pointcut sub() : execution(* Base+.*(..));
pointcut notBase() : ! execution(* Base.*(..));
pointcut cons() : execution(public Base+.new(..)) && ! execution(public Base.new(..));
//advice sub class methods but not annotation or parent
Object around() : sub_nonannotated() && sub() && notBase() {
return proceed();
}
//Advice subclass constructors but not Base's constructor
Object around() : cons() {
return proceed();
}
}

Adam Gent's solution is way too complex. This pointcut is simpler and clearer:
execution(!#LeaveItAlone * Base+.*(..))
Or alternatively, maybe you like it better (a matter of taste):
execution(* Base+.*(..)) && !#annotation(LeaveItAlone)
P.S.: This only takes care of methods, not of constructors, which is what you asked for in your first sentence. I also includes methods of Base itself, not just subclasses, which probably makes sense. If you wanted a more complex thing, you can still combine my solution with the elements from Adam's.

Related

AspectJ advice on method of a class that has a field

I want to write an around advice to set a correlation-id into MDC before the invocation of proceed() and return the old value after it. Here is how far I got:
public aspect CorrelationIdAspect
{
private pointcut notPrivateMethod() :
execution(!private * *(..));
private pointcut methodWithContract(Contract contract) :
execution( * *.*(Contract, ..)) && args(contract, ..);
Object around(Contract contract) : methodWithContract(contract) && notPrivateMethod()
{
String oldCorrelationId = MDC.get(Constants.CORRELATION_ID);
try
{
String id = contract.getId().toString();
MDC.put(Constants.CORRELATION_ID, id);
Object result = proceed(contract);
return result;
}
finally
{
MDC.put(Constants.CORRELATION_ID, oldCorrelationId);
}
}
}
Now I want that this advice should only be applied to classes that have a field of type
org.apache.logging.log4j.Logger
because - obviously - a class that has no logger doesn't need to have the correlation id set and restored. Has anybody an idea how that can be accomplished?
Many thanks in advance!
You want to use compiler option -XhasMember (see also my other answer), to be found in Eclipse here:
Then you
add a marker interface to your aspect,
use ITD in order to declare that each class having a static Logger field ought to implement that interface and
match on the marker interface and all its implementing classes:
public aspect CorrelationIdAspect {
// 1. marker interface
private interface HasLogger {}
// 2. use ITD in order to declare that each class having a
// 'static Logger' field ought to implement that interface
declare parents :
hasfield(static Logger *) implements HasLogger;
private pointcut notPrivateMethod() :
execution(!private * *(..));
// 3. match on the marker interface and all its implementing classes
private pointcut hasLogger() :
within(HasLogger+);
private pointcut methodWithContract(Contract contract) :
execution(* *(Contract, ..)) && args(contract, ..);
Object around(Contract contract) :
methodWithContract(contract) && notPrivateMethod() && hasLogger()
{
System.out.println(thisJoinPoint);
return proceed(contract);
}
}

In TypeScript, how to prevent a method from being called on derived class?

There are three classes.
// in external library, which I don't want to modify
class ComponentBase {
// I want calling this to be disallowed
forceUpdate() {}
}
class ComponentBase_MyVersion extends ComponentBase {
// I want subclasses to always call this, instead of forceUpdate()
Update() {}
}
class MyComponent extends ComponentBase_MyVersion {
DoSomething() {
// I want this to be disallowed
this.forceUpdate();
// forcing the subclass to call this instead
this.Update();
}
}
How can I accomplish this, with changes only to ComponentBase_MyVersion?
Is there a way to "hide" a base-class member?
Or perhaps a way to override the definition -- like with the "new" keyword in C# -- letting me mangle the method definition to at least make warnings appear when attempting to call it?
The OOP does not allow you to do this kind of method cancellation. You can impleement this funcion on your class with an Exception like you suggested, or use a composition: https://en.wikipedia.org/wiki/Composition_over_inheritance
Example 1:
class ComponentBase {
forceUpdate() {}
}
class ComponentBase_MyVersion extends ComponentBase {
Update() {}
forceUpdate() {
throw new Error("Do not call this. Call Update() instead.");
}
}
class MyComponent extends ComponentBase_MyVersion {
DoSomething() {
// wil raise an exception
this.forceUpdate();
this.Update();
}
}
Example 2 (composition):
class ComponentBase {
forceUpdate() {}
}
class ComponentBase_MyVersion {
private _component: ComponentBase = ...;
Update() {}
// expose _component desired members ...
}
class MyComponent extends ComponentBase_MyVersion {
DoSomething() {
// compilation error
this.forceUpdate();
this.Update();
}
}
I hope I helped.
Encapsulate implementation by replacing inheritance with composition Delegation Pattern
You can do this by adding the private access modifier on the forceUpdate method. This will result in all the subclasses being unable to access forceUpdate. However TypeScript does not support package access modifiers, but you can do this by replacing inheritance with composition.
class ComponentBase {
forceUpdate() {
}
}
class ComponentBase_MyVersion {
// Replace inheritance with composition.
private component: ComponentBase;
Update() {
this.component.forceUpdate();
}
}
class MyComponent extends ComponentBase_MyVersion {
DoSomething() {
// Now subclass can't access forceUpdate method
this.Update();
}
}
Use a symbol in order to prevent external access to the method.
If you don't want to replace inheritance with composition, you can use Symbol to define a method. If your target is es5 you must configure tsconfig.json compilerOptions.lib to include es2015.symbol. Because every symbol is unique, any external module will not be able to obtain the symbol and access the method.
// libs.ts
let forceUpdate = Symbol("forceUpdate");
export class ComponentBase {
[forceUpdate]() {
}
}
export default class ComponentBase_MyVersion extends ComponentBase {
Update() {
this[forceUpdate]();
}
}
// test.ts
import ComponentBase_MyVersion from "./libs";
class MyComponent extends ComponentBase_MyVersion {
DoSomething() {
// Now subclass can't access the forceUpdate method.
this.Update();
}
}
I found a way that seems to work -- that is, which causes warnings to appear when someone attempts to call forceUpdate() on a subclass instance.
forceUpdate(_: ()=>"Do not call this. Call Update() instead.") {
throw new Error("Do not call this. Call Update() instead.");
}
Now when I write new MyComponent().forceUpdate(), I get a compiler error, with the warning message containing a description telling me to use Update() instead.
EDIT: Apparently this only works because the base class already had this definition:
forceUpdate(callBack?: () => any): void;
If instead the base method is defined with no arguments originally (as in the OP), the above solution doesn't work.
However, if you have a case like mine (where there's an optional property like that, which you can narrow the return-type of), it works fine. (not sure if this return-type-narrowing is a bug, or intended)

Pointcut for method with call of the specific method inside

I have method A and method B. I want pointcut to be attached to the method A, only if method B is called in method A.
Is it possible with Aspets? Thank you.
Example:
Aspect Code:
package aspects.unregistrator;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import com.core.Item;
public aspect Unregistrator {
pointcut unRegistrated() : within(tasks..*) && call(* find(..));
after() : unRegistrated() {
Item.unregisterAll();
}
}
this will attach point after every call of find() in every method in tasks package
but I need unregisterAll() to be executed after every method that contains find() call, like this:
package tasks.helpers;
public class TableHelper {
public static void clickButtonInCell(final WTable table) {
table.find(SubitemFactory(Element.BUTTON)).click();
Item.unregisterAll();
}
I have just found one way to make this possible using two special keywords of the AspectJ language: thisEnclosingJoinPointStaticPart and thisJoinPointStaticPart. In this way, you need to keep the enclosing join points where the find() method being called (in your case public static void clickButtonInCell(final WTable table)). Then, you need to check each method execution whether the enclosing join point of the find() method is the same as its join point.
For example:
class TableHelper {
public static void clickButtonInCell(final WTable table) {
System.out.println("clickButtonInCell");
table.find();
// Item.unregisterAll() will be called after find()
}
public static void clickButtonInX(final WTable table) {
System.out.println("clickButtonInX");
table.doSomething();
// even if Item.unregisterAll() is matched with this method execution, it will not work
}
}
public aspect Unregistrator {
String enclosedJP = "";
pointcut unRegistrated() : within(tasks..*) && call(* find(..));
after() : unRegistrated() {
enclosedJP = thisEnclosingJoinPointStaticPart.toLongString();
}
pointcut doPointcut(): within(tasks..*) && execution(* *(..));
after() : doPointcut(){
if(enclosedJP.equals(thisJoinPointStaticPart.toLongString()))
Item.unregisterAll();
}
}
I hope this helps what you need.

How do I mock Class<? extends List> myVar in Mockito?

I want to mock a Class in Mockito. It will then have a .newInstance() call issued which will be expected to return an actual class instance (and will return a mock in my case).
If it was setup correctly then I could do:
ArrayList myListMock = mock(ArrayList.class);
when(myVar.newInstance()).thenReturn(myListMock);
I know I can set it up so that a new instance of class ArrayList will be a mock (using PowerMockito whenNew), just wondering if there was a way to mock this kind of a class object so I don't have to override instance creation...
Below is the real class I'm trying to mock, I can't change the structure it is defined by the interface. What I'm looking for is a way to provide cvs when initialize is called.
public class InputConstraintValidator
implements ConstraintValidator<InputValidation, StringWrapper> {
Class<? extends SafeString> cvs;
public void initialize(InputValidation constraintAnnotation) {
cvs = constraintAnnotation.inputValidator();
}
public boolean isValid(StringWrapper value,
ConstraintValidatorContext context) {
SafeString instance;
try {
instance = cvs.newInstance();
} catch (InstantiationException e) {
return false;
} catch (IllegalAccessException e) {
return false;
}
}
Mockito is designed exclusively for mocking instances of objects. Under the hood, the mock method actually creates a proxy that receives calls to all non-final methods, and logs and stubs those calls as needed. There's no good way to use Mockito to replace a function on the Class object itself. This leaves you with a few options:
I don't have experience with PowerMock but it seems it's designed for mocking static methods.
In dependency-injection style, make your static factory method into a factory instance. Since it looks like you're not actually working with ArrayList, let's say your class is FooBar instead:
class FooBar {
static class Factory {
static FooBar instance;
FooBar getInstance() {
if (instance == null) {
instance = new FooBar();
}
return instance;
}
}
// ...
}
Now your class user can receive a new FooBar.Factory() parameter, which creates your real FooBar in singleton style (hopefully better and more threadsafe than my simple implementation), and you can use pure Mockito to mock the Factory. If this looks like it's a lot of boilerplate, it's because it is, but if you are thinking of switching to a DI solution like Guice you can cut down a lot of it.
Consider making a field or method package-private or protected and documenting that it's visible for testing purposes. Then you can insert a mocked instance in test code only.
public class InputConstraintValidator implements
ConstraintValidator<InputValidation, StringWrapper> {
Class<? extends SafeString> cvs;
public void initialize(InputValidation constraintAnnotation) {
cvs = constraintAnnotation.inputValidator();
}
public boolean isValid(StringWrapper value,
ConstraintValidatorContext context) {
SafeString instance;
try {
instance = getCvsInstance();
} catch (InstantiationException e) {
return false;
} catch (IllegalAccessException e) {
return false;
}
}
#VisibleForTesting protected getCvsInstance()
throws InstantiationException, IllegalAccessException {
return cvs.newInstance();
}
}
public class InputConstaintValidatorTest {
#Test public void testWithMockCvs() {
final SafeString cvs = mock(SafeString.class);
InputConstraintValidator validator = new InputConstraintValidator() {
#Override protected getCvsInstance() {
return cvs;
}
}
// test
}
}
I think you just need to introduce an additional mock for Class:
ArrayList<?> myListMock = mock(ArrayList.class);
Class<ArrayList> clazz = mock(Class.class);
when(clazz.newInstance()).thenReturn(myListMock);
Of course the trick is making sure your mocked clazz.newInstance() doesn't end up getting called all over the place because due to type-erasure you can't specify that it's actually a Class<ArrayList>.
Also, be careful defining your own mock for something as fundamental as ArrayList - generally I'd use a "real one" and populate it with mocks.

Should I use an interface or factory (and interface) for a cross-platform implementation?

Example A:
// pseudo code
interface IFoo {
void bar();
}
class FooPlatformA : IFoo {
void bar() { /* ... */ }
}
class FooPlatformB : IFoo {
void bar() { /* ... */ }
}
class Foo : IFoo {
IFoo m_foo;
public Foo() {
if (detectPlatformA()} {
m_foo = new FooPlatformA();
} else {
m_foo = new FooPlatformB();
}
}
// wrapper function - downside is we'd have to create one
// of these for each function, which doesn't seem right.
void bar() {
m_foo.bar();
}
}
Main() {
Foo foo = new Foo();
foo.bar();
}
Example B:
// pseudo code
interface IFoo {
void bar();
}
class FooPlatformA : IFoo {
void bar() { /* ... */ }
}
class FooPlatformB : IFoo {
void bar() { /* ... */ }
}
class FooFactory {
IFoo newFoo() {
if (detectPlatformA()} {
return new FooPlatformA();
} else {
return new FooPlatformB();
}
}
}
Main() {
FooFactory factory = new FooFactory();
IFoo foo = factory.newFoo();
foo.bar();
}
Which is the better option, example A, B, neither, or "it depends"?
I would say that your explicit factory option (option B) is generally better.
In your first example your Foo class is effectively doing two jobs, it's a factory and it's a proxy. Two jobs, one class, makes me uneasy.
Your second option puts a little more responsibility on the client: they need to know to use the factory, but this is such a widely used idiom that I think it's not hard to understand.
The problem with A is that you have to implement every method of IFoo in Foo. That is not a big deal if there are only a couple, but is a pain if there are dozens of them. If you are working with a language that supports factory methods, such as Curl, then you could put a factory method in IFoo:
{define-class abstract IFoo
{method abstract {bar}:void}
{factory {default}:{this-class}
{if platformA? then
{return {FooPlatformA}}
else
{return {FooPlatformB}}
}
}
}
{define-class FooPlatformA {inherits IFoo}
{method {bar}:void}
}
...
def foo = {IFoo}
{foo.bar}
If you ask me B is way better - since Foo itself does not need to do any switching on platform. Why does that matter? Well, since you probably want to test all components separately - Foo with a 'test' IFoo, FooPlatformA separately on platform A and FooPlatformB on platform B. If you stick the choice inside Foo you need to test Foo on both A and B, not only the different IFoos. Makes the components more coupled for no apparent reason.
The factory is a cleaner solution as you do not have implement each member of the interface in the wrapper class Foo : IFoo. Imagine, each time you modify the IFoo interface you would need update the wrapper. When programming, depending on your goals, try to consider maintainability as much as possible.
Are all 'platforms' available or only one of them? Is the only difference between the platforms is logic? Thinking from a game developer perspective I would use #defines to implement this.
class Platform : IPlatform
{
void Update()
{
#if PLATFORM_A
* ... Logic for platform A */
#elif PLATFORM_B
* ... Logic for platform A */
#endif
}
}
HTH,
Interfaces are used when it is possible that multiple implementations of a single functional set may exist. This sounds as though it applies to your particular scenario.
In terms of your examples, I would definitely roll with B, it is easier to maintain. A embeds too much common logic [ie platform detection] within individual classes [and/or methods]. If you are to build your own Factory class, try to generalize it [through a generic Resolve<IType> () method or something], as opposed to a method\class per interface.
For instance,
// i called it a "container" because it "contains" implementations
// or instantiation methods for requested types - but it *is* a
// factory.
public class Container
{
// "resolves" correct implementation for a requested type.
public IType Resolve<IType> ()
{
IType typed = default (IType);
if (isPlatformA)
{
// switch or function map on IType for correct
// platform A implementation
}
else if (isPlatformB)
{
// switch or function map on IType for correct
// platform B implementation
}
else
{
// throw NotSupportedException
}
return typed;
}
}
However, rather than implement your own Factory pattern, you may wish to investigate alternative implementations, such as MS's Unity2.0 or Castle Windsor's CastleWindsorContainer. These are easy to configure and consume.
Ideally,
// use an interface to isolate *your* code from actual
// implementation, which could change depending on your needs,
// for instance if you "roll your own" or switch between Unity,
// Castle Windsor, or some other vendor
public interface IContainer
{
IType Resolve<IType> ();
}
// custom "roll your own" container, similar to above,
public class Container : IContainer { }
// delegates to an instance of a Unity container,
public class UnityContainer : IContainer { }
// delegates to an instance of a CastleWindsorContainer,
public class CastleWindsorContainer : IContainer { }
Oh, suppose I ought to shout out to Ninject and StructureMap too. I am just not as familiar with these as with Unity or CastleWindsor.