List of usage examples for org.aspectj.lang ProceedingJoinPoint getSignature
Signature getSignature();
getStaticPart().getSignature()
returns the same object From source file:com.crossbusiness.resiliency.aspect.AbstractGovernorAspect.java
License:Open Source License
protected Object wrap(final ProceedingJoinPoint pjp, Governor governorConfig) throws Throwable { // throttle per instance, per method String throttleKey = pjp.getTarget().hashCode() + pjp.getSignature().toLongString(); if (!throttles.containsKey(throttleKey)) { switch (governorConfig.type()) { case CONCURRENCY: throttles.put(throttleKey,//from w ww . ja va2 s .co m new ConcurrencyThrottleDecorator(governorConfig.limit(), governorConfig.blocking())); break; case RATE: throttles.put(throttleKey, new RateThrottleDecorator(governorConfig.limit(), governorConfig.period(), governorConfig.unit(), governorConfig.blocking(), scheduler)); break; case ALL: //TODO break; default: log.error("Unknown Throttler type"); break; } } Throttler t = throttles.get(throttleKey); if (t != null) { return t.proceed(pjp); } else { log.error("no throttles found"); return pjp.proceed(); } }
From source file:com.crossbusiness.resiliency.aspect.AbstractTimeout2Aspect.java
License:Open Source License
public Object doTimeout(final ProceedingJoinPoint point, Timeout2 timeoutConfig) throws Throwable { log.debug(point + " -> " + timeoutConfig); Method method = ((MethodSignature) point.getSignature()).getMethod(); TimeoutThread thread = new TimeoutThread(); thread.setDaemon(timeoutConfig.daemon()); thread.setPoint(point);//from ww w . j a va2 s . c o m thread.start(); thread.join(timeoutConfig.unit().toMillis(timeoutConfig.value())); if (!thread.isCompleted()) { throw new TimeoutException("Method " + method + " exceeded timeout of " + timeoutConfig.unit().toMillis(timeoutConfig.value()) + " ms"); } else if (thread.getThrowable() != null) { throw thread.getThrowable(); } else { return thread.getValue(); } }
From source file:com.crossbusiness.resiliency.aspect.spring.AnnotationFallbackAspect.java
License:Open Source License
public Object rerouteToFallback(ProceedingJoinPoint pjp, Fallback fallbackConfig) throws Throwable { String[] fallbacks = fallbackConfig.value(); Class<? extends Throwable>[] fallbackableExceptions = fallbackConfig.exceptions(); List<Object> fallbackBeans = new ArrayList<Object>(fallbacks.length); for (String fallback : fallbacks) { try {// w w w .ja v a 2 s . com fallbackBeans.add(context.getBean(fallback)); } catch (BeansException be) { log.error("configuration error: cannot find bean with name: '{}'", fallback, be); //configuration errors should be fixed immediately. throw be; } } MethodSignature targetMethodSig = (MethodSignature) pjp.getSignature(); Method targetMethod = targetMethodSig.getMethod(); Class[] paramTypes = (Class[]) targetMethod.getParameterTypes(); Object[] args = pjp.getArgs(); log.debug("fallbacks: {} method: '{}'", fallbacks, targetMethod); try { return pjp.proceed(); } catch (Throwable t) { // if the exception is not what we're looking for, rethrow it if (!isFallbackableException(t, fallbackableExceptions)) throw t; log.debug("got exception while trying the targetBean method: '{}'. will try fallbackBean...", targetMethod); Iterator<Object> iter = fallbackBeans.iterator(); while (iter.hasNext()) { Object fallbackBean = iter.next(); Method fallbackMethod; try { fallbackMethod = fallbackBean.getClass().getMethod(targetMethod.getName(), paramTypes); } catch (NoSuchMethodException | SecurityException nsme) { log.error( "configuration error: No matchig method found in fallbackBean: '{}' that matches to targetBean method: '{}'", new Object[] { fallbackBean.getClass().getName(), targetMethod, nsme }); //configuration errors should be fixed immediately. throw nsme; } try { log.debug("trying fallbackBean method: '{}'...", fallbackMethod); return fallbackMethod.invoke(fallbackBean, args); } catch (IllegalArgumentException | IllegalAccessException iae) { log.error( "configuration error: arguments missmatch: fallbackBean method: '{}' arguments missmatch to targetBean method: '{}' arguments", new Object[] { fallbackMethod, targetMethod, iae }); //configuration errors should be fixed immediately. throw iae; } catch (InvocationTargetException ite) { log.debug( "got exception while trying the fallbackBean method: '{}'. will try next fallbackBean...", fallbackMethod); //fallbackBean method thrown an exception. try next bean or throw exception if this is the last bean if (!iter.hasNext()) { //TODO : do we still need to check isFallbackableException? throw ite.getCause(); } } } //code should never reach this line. throw t; } }
From source file:com.daphne.es.extra.aop.UserCacheAspect.java
License:Apache License
@Around(value = "userServicePointcut() && cacheablePointcut()") public Object cacheableAdvice(ProceedingJoinPoint pjp) throws Throwable { String methodName = pjp.getSignature().getName(); Object arg = pjp.getArgs().length >= 1 ? pjp.getArgs()[0] : null; String key = ""; boolean isIdKey = false; if ("findOne".equals(methodName)) { key = idKey(String.valueOf(arg)); isIdKey = true;//from w w w .j a v a 2s . c o m } else if ("findByUsername".equals(methodName)) { key = usernameKey((String) arg); } else if ("findByEmail".equals(methodName)) { key = emailKey((String) arg); } else if ("findByMobilePhoneNumber".equals(methodName)) { key = mobilePhoneNumberKey((String) arg); } User user = null; if (isIdKey == true) { user = get(key); } else { Long id = get(key); if (id != null) { key = idKey(String.valueOf(id)); user = get(key); } } //cache hit if (user != null) { log.debug("cacheName:{}, hit key:{}", cacheName, key); return user; } log.debug("cacheName:{}, miss key:{}", cacheName, key); //cache miss user = (User) pjp.proceed(); //put cache put(user); return user; }
From source file:com.datastax.hectorjpa.spring.ConsistencyLevelAspect.java
License:Open Source License
/** * Validates any method that has the valid annotation on it and is wired as * a spring service//from w w w .j a v a 2s .c o m * * @param jp * @throws Throwable */ @Around("@annotation(com.datastax.hectorjpa.spring.Consistency)") public Object setConsistency(ProceedingJoinPoint pjp) throws Throwable { logger.debug("Invoking before advice for @Consistency annotation. Target object is {} on method {}", pjp.getTarget(), pjp.getSignature()); MethodSignature sig = (MethodSignature) pjp.getSignature(); Object[] args = pjp.getArgs(); Method signatureMethod = sig.getMethod(); Class<?>[] signatureTypes = signatureMethod.getParameterTypes(); // we do this because we want to get the best match from the child // classes Class<?>[] runtimeArgs = new Class<?>[signatureTypes.length]; for (int i = 0; i < signatureTypes.length; i++) { if (args[i] != null) { runtimeArgs[i] = args[i].getClass(); } else { runtimeArgs[i] = signatureTypes[i]; } } Class<?> runtimeClass = pjp.getTarget().getClass(); // check if this is annotated, if not proceed and execute it HConsistencyLevel level = consistency(runtimeClass, signatureMethod.getName(), runtimeArgs); if (level == null) { return pjp.proceed(args); } Stack<HConsistencyLevel> stack = threadStack.get(); stack.push(level); JPAConsistency.set(level); Object result = null; try { result = pjp.proceed(args); } finally { stack.pop(); if (stack.size() > 0) { JPAConsistency.set(stack.peek()); } else { JPAConsistency.remove(); } } return result; }
From source file:com.devexperts.chameleon.aspect.TimingAspect.java
License:Open Source License
@Around("serviceMethods()") public Object profile(ProceedingJoinPoint pjp) throws Throwable { Signature signature = pjp.getSignature(); String name = signature.toShortString(); long start = System.currentTimeMillis(); Object output = pjp.proceed(); long elapsedTime = System.currentTimeMillis() - start; if (elapsedTime > timingMoreThen) logger.info("{} execution time: " + elapsedTime + " milliseconds.", name); return output; }
From source file:com.dianping.wed.cache.redis.aop.RedisAspect.java
License:Open Source License
public Object doAround(ProceedingJoinPoint pjp) throws Throwable { Object result = null;/*from w ww . ja va2 s.co m*/ String op = pjp.getSignature().getName() + ":(RedisKeys)"; //Cat.logMetricForCount(CAT_NAME.concat(op)); Transaction transaction = Cat.getProducer().newTransaction(CAT_NAME, op); try { result = pjp.proceed(); transaction.setStatus(Transaction.SUCCESS); } catch (Exception e) { transaction.setStatus(e); Cat.logError(e); throw e; } finally { transaction.complete(); } return result; }
From source file:com.eryansky.core.aop.LogAspect.java
License:Apache License
/** * @param point /*from w ww.jav a2s. co m*/ */ @Around("execution(* com.eryansky.service..*Manager.*(..))") public Object logAll(ProceedingJoinPoint point) { Object result = null; // ?? String methodName = point.getSignature().getName(); String className = point.getTarget().getClass().getSimpleName(); String userName = null; Long start = 0L; Long end = 0L; String ip = null; // ? try { // start = System.currentTimeMillis(); result = point.proceed(); end = System.currentTimeMillis(); // ?? SessionInfo sessionInfo = SecurityUtils.getCurrentSessionInfo(); if (sessionInfo != null) { userName = sessionInfo.getLoginName(); ip = sessionInfo.getIp(); } else { userName = ""; ip = "127.0.0.1"; logger.warn("sessionInfo."); } } catch (Throwable e) { logger.error(e.getMessage()); // e.printStackTrace(); } String name = null; // ? if (className.indexOf("Resource") > -1) { name = "??"; } else if (className.indexOf("Role") > -1) { name = "?"; } else if (className.indexOf("User") > -1) { name = "?"; } else if (className.indexOf("Organ") > -1) { name = "?"; } else { name = className; } // ? String opertype = methodName; if (StringUtils.isNotBlank(opertype) && (opertype.indexOf("save") > -1 || opertype.indexOf("update") > -1 || opertype.indexOf("delete") > -1 || opertype.indexOf("merge") > -1)) { Long time = end - start; Log log = new Log(); log.setType(LogType.operate.getValue()); log.setLoginName(userName); log.setModule(name); log.setAction(opertype); log.setOperTime(new Date(start)); log.setActionTime(time.toString()); log.setIp(ip); defaultEntityManager.save(log); } if (logger.isDebugEnabled()) { logger.debug(":{},?{},?{},{}ms.", new Object[] { userName, className, methodName, end - start }); } return result; }
From source file:com.evolveum.midpoint.util.aspect.MidpointAspect.java
License:Apache License
private Object wrapSubsystem(ProceedingJoinPoint pjp, String subsystem) throws Throwable { Object retValue = null;/* w ww . j av a2s . c o m*/ String prev = null; int id = 0; int d = 1; boolean exc = false; String excName = null; long elapsed; // Profiling start long startTime = System.nanoTime(); final StringBuilder infoLog = new StringBuilder("#### Entry: "); try { // Marking MDC->Subsystem with current one subsystem and mark // previous prev = swapSubsystemMark(subsystem); if (LOGGER_PROFILING.isDebugEnabled()) { id = idcounter.incrementAndGet(); infoLog.append(id); } if (LOGGER_PROFILING.isTraceEnabled()) { String depth = MDC.get("depth"); if (depth == null || depth.isEmpty()) { d = 0; } else { d = Integer.parseInt(depth); } d++; MDC.put("depth", Integer.toString(d)); for (int i = 0; i < d; i++) { infoLog.append(INDENT_STRING); } } // is profiling info is needed if (LOGGER_PROFILING.isDebugEnabled()) { infoLog.append(getClassName(pjp)); LOGGER_PROFILING.debug("{}->{}", infoLog, pjp.getSignature().getName()); // If debug enable get entry parameters and log them if (LOGGER_PROFILING.isTraceEnabled()) { final Object[] args = pjp.getArgs(); // final String[] names = ((CodeSignature) // pjp.getSignature()).getParameterNames(); // @SuppressWarnings("unchecked") // final Class<CodeSignature>[] types = ((CodeSignature) // pjp.getSignature()).getParameterTypes(); final StringBuffer sb = new StringBuffer(); sb.append("###### args: "); sb.append("("); for (int i = 0; i < args.length; i++) { sb.append(formatVal(args[i])); if (args.length != i + 1) { sb.append(", "); } } sb.append(")"); LOGGER_PROFILING.trace(sb.toString()); } } //We dont need profiling on method start in current version // if profiling info is needed - start //if(isProfilingActive){ // LOGGER.info("Profiling is active: onStart"); // AspectProfilingFilters.applyGranularityFilterOnStart(pjp, subsystem); //} // Process original call try { retValue = pjp.proceed(); } catch (Exception e) { excName = e.getClass().getName(); exc = true; throw e; } // Return original response return retValue; } finally { // Depth -1 if (LOGGER_PROFILING.isTraceEnabled()) { d--; MDC.put("depth", Integer.toString(d)); } // Restore previously marked subsystem executed before return if (LOGGER_PROFILING.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("##### Exit: "); if (LOGGER_PROFILING.isDebugEnabled()) { sb.append(id); sb.append(" "); } // sb.append("/"); if (LOGGER_PROFILING.isTraceEnabled()) { for (int i = 0; i < d + 1; i++) { sb.append(INDENT_STRING); } } sb.append(getClassName(pjp)); sb.append("->"); sb.append(pjp.getSignature().getName()); if (LOGGER_PROFILING.isDebugEnabled()) { sb.append(" etime: "); // Mark end of processing elapsed = System.nanoTime() - startTime; sb.append((long) (elapsed / 1000000)); sb.append('.'); long mikros = (long) (elapsed / 1000) % 1000; if (mikros < 100) { sb.append('0'); } if (mikros < 10) { sb.append('0'); } sb.append(mikros); sb.append(" ms"); } LOGGER_PROFILING.debug(sb.toString()); if (LOGGER_PROFILING.isTraceEnabled()) { if (exc) { LOGGER_PROFILING.trace("###### return exception: {}", excName); } else { LOGGER_PROFILING.trace("###### retval: {}", formatVal(retValue)); } } } if (isProfilingActive) { if (pjp != null) { Long processingStartTime = System.nanoTime(); ProfilingDataManager.getInstance().applyGranularityFilterOnEnd(getClassName(pjp), getMethodName(pjp), pjp.getArgs(), subsystem, startTime, processingStartTime); } } // Restore MDC swapSubsystemMark(prev); } }
From source file:com.evolveum.midpoint.util.aspect.MidpointAspect.java
License:Apache License
private String getMethodName(ProceedingJoinPoint pjp) { return pjp.getSignature().getName(); }