Skip to content

Instantly share code, notes, and snippets.

@ihopeudie
Created October 9, 2018 08:13
Show Gist options
  • Save ihopeudie/14af719a155f96bc56ae9f1919b01626 to your computer and use it in GitHub Desktop.
Save ihopeudie/14af719a155f96bc56ae9f1919b01626 to your computer and use it in GitHub Desktop.
package com.epamacademy.springcource.movietheater.aspects;
import com.epamacademy.springcource.movietheater.domain.Event;
import com.epamacademy.springcource.movietheater.util.CounterType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
/*
CounterAspect - count how many times each event was accessed by name,
how many times its prices were queried,
how many times its tickets were booked.
Store counters in map for now (later could be replaced by DB dao)
*/
@Aspect
public class CounterAspect {
private Map<Event, Map<CounterType, AtomicLong>> counterAspectMap;
@PostConstruct
private void init() {
counterAspectMap = new HashMap<>();
}
@Pointcut("execution(* com.epamacademy.springcource.movietheater.domain.Event.getBasePrice())")
private void increasePriceRequestCounter() {}
@AfterReturning(pointcut = "increasePriceRequestCounter()")
private void addPriceRequestCounter() {
System.out.println("qwe");
//addEvent((Event)joinPoint.getThis(),CounterType.PRICES_QUERIED);
}
@Pointcut("execution(* com.epamacademy.springcource.movietheater.dao.EventDao.getByName(String))")
private void increaseByNameCounter() {
}
@AfterReturning(pointcut = "increaseByNameCounter()",
returning = "event"
)
private void addGetByNameCounter(Event event) {
addEvent(event,CounterType.ACCESSED_BY_NAME);
}
Map<Event, Map<CounterType, AtomicLong>> getCounterAspectMap() {
return counterAspectMap;
}
private void addEvent(Event event, CounterType type) {
Map<CounterType, AtomicLong> recordMap = counterAspectMap.get(event);
if (recordMap == null || recordMap.get(type) == null) {
recordMap = new HashMap<>();
recordMap.put(type, new AtomicLong(1));
}
else {
recordMap.replace(type,new AtomicLong(recordMap.get(type).incrementAndGet()));
}
counterAspectMap.put(event, recordMap);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment