javaaspectjpointcut

AspectJ pointcuts and advice to capture the method call from one Java class to another


I have two classes Server and Client as follows:

import java.util.*;
public class Server {
    private String name;
    private ArrayList<Client> clients = new ArrayList<Client>();

    public Server(String name) {
        this.name = name;
        this.active = true;
    }

    public void attach (Client client) {
        clients.add(client);
    }

    public String ping() {
        return "PING ";
    }

}

public class Client {
    private String name;
    private String address;
    private Server server;

    public Client(String name, String address) {
        this.name = name;
        this.address = address;
    }

    public void connect(Server server) {
        this.server = server;
        server.attach(this);
    }

    public String pingServer() {
        return server.ping();
    }

}

I want to write a pointcut to capture any message sent from the client to the server and advice to execute before allowing the message to be sent. The code I have written is as follows:

Pointcut

pointcut chckDomain (Server s, Client c) : call (* Client.*(..)) 
                                            && target(s)
                                            && this(c);

Advice

Object around(Server s, Client c) : chckDomain(s, c) {
        System.out.println("checkDomain");
        proceed(s, c);
        return null;
    }

I was able to achieve the desired result using before advice. But I want to resume the normal execution after doing some checks in the advice which is why I am using around advice as shown above. However, this is not capturing the message invocation. Please not that the client and server classes have additional methods with different return types and different parameters which is why I cannot hardcode them. I have used the following code in the main method for the test.

Server university = new Server("MyUniversity");
Client mark = new Client("Mark", "student.edu");
mark.connect(university);
System.out.println(mark.pingServer());

I could not find proper documentation for AscpectJ except for the Eclipse documentation. Any guidance would be appreciated.


Solution

  • Solved it using the following pointcut:

    pointcut chckDomain (Server s, Client c) : call (* Server.*(..)) 
                                                    && this(c)
                                                    && target(s);
    

    And the following advice:

    Object around(Server s, Client c) : chckDomain(s, c) {
    System.out.println("checkDomain");
        proceed(s, c);
        return null;
    }
    

    I was supposed to capture all the calls to Server class which is why I replaced Client to Server in the pointcut.