@ExceptionHandler(Exception.class) public ResponseEntity<ErrorVM> processException(Exception ex) { log.error("An unexpected error occurred: {}", ex.getMessage(), ex); BodyBuilder builder; ErrorVM errorVM; ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class); if (responseStatus != null) { builder = ResponseEntity.status(responseStatus.value()); errorVM = new ErrorVM(ERROR_PREFIX + responseStatus.value().value(), translate(ERROR_PREFIX + responseStatus.value().value())); } else { builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR); errorVM = new ErrorVM(ErrorConstants.ERR_INTERNAL_SERVER_ERROR, translate(ErrorConstants.ERR_INTERNAL_SERVER_ERROR)); } return builder.body(errorVM); }
@ExceptionHandler(Exception.class) public ResponseEntity<ErrorVM> processException(Exception ex) { if (log.isDebugEnabled()) { log.debug("An unexpected error occurred: {}", ex.getMessage(), ex); } else { log.error("An unexpected error occurred: {}", ex.getMessage()); } BodyBuilder builder; ErrorVM errorVM; ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class); if (responseStatus != null) { builder = ResponseEntity.status(responseStatus.value()); errorVM = new ErrorVM("error." + responseStatus.value().value(), responseStatus.reason()); } else { builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR); errorVM = new ErrorVM(ErrorConstants.ERR_INTERNAL_SERVER_ERROR, "Internal server error"); } return builder.body(errorVM); }
private void injectServicesViaAnnotatedFields(final Object bean, final String beanName) { ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() { public void doWith(Field field) { ServiceReference s = AnnotationUtils.getAnnotation(field, ServiceReference.class); if (s != null && !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) { try { if (logger.isDebugEnabled()) logger.debug("Processing annotation [" + s + "] for [" + field + "] on bean [" + beanName + "]"); if (!field.isAccessible()) { field.setAccessible(true); } ReflectionUtils.setField(field, bean, getServiceImporter(s, field.getType(), beanName).getObject()); } catch (Exception e) { throw new IllegalArgumentException("Error processing service annotation", e); } } } }); }
@ExceptionHandler(Exception.class) public ResponseEntity<ErrorVM> processException(Exception ex) { if (log.isDebugEnabled()) { log.debug("An unexpected error occured: {}", ex.getMessage(), ex); } else { log.error("An unexpected error occured: {}", ex.getMessage()); } BodyBuilder builder; ErrorVM errorVM; ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class); if (responseStatus != null) { builder = ResponseEntity.status(responseStatus.value()); errorVM = new ErrorVM("error." + responseStatus.value().value(), responseStatus.reason()); } else { builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR); errorVM = new ErrorVM(ErrorConstants.ERR_INTERNAL_SERVER_ERROR, "Internal server error"); } return builder.body(errorVM); }
@ExceptionHandler(Exception.class) public ResponseEntity<ErrorVM> processRuntimeException(Exception ex) { BodyBuilder builder; ErrorVM errorVM; ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class); if (responseStatus != null) { builder = ResponseEntity.status(responseStatus.value()); errorVM = new ErrorVM("error." + responseStatus.value().value(), responseStatus.reason()); } else { builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR); errorVM = new ErrorVM(ErrorConstants.ERR_INTERNAL_SERVER_ERROR, "Internal server error"); } return builder.body(errorVM); }
private static void collectParameters(Collection<Parameters> parameters, Parameter parameter, Annotation a, boolean isPathVariable) { if (a != null) { String typeStr = parameter.getType().getSimpleName(); Type type = parameter.getParameterizedType(); if (type instanceof ParameterizedType) { typeStr = ((Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0]).getSimpleName(); } parameters.add(new Parameters((boolean) AnnotationUtils.getValue(a, "required"), (String) (AnnotationUtils.getValue(a).equals("") ? parameter.getName() : AnnotationUtils.getValue(a)), typeStr)); } else if (Pageable.class.isAssignableFrom(parameter.getType()) && !isPathVariable) { try { for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(parameter.getType()) .getPropertyDescriptors()) { parameters.add(new Parameters(false, propertyDescriptor.getName(), propertyDescriptor.getPropertyType().getSimpleName())); } } catch (IntrospectionException e) { LOGGER.error("Problemas al obtener el Pageable: {}", parameter, e); } } }
@Around("interceptDao()") public Object intercept(ProceedingJoinPoint joinPoint) throws Throwable { Object result = null; try { Class clazz = MethodSignature.class.cast(joinPoint.getSignature()).getDeclaringType(); DynamicDS targetDataSource = AnnotationUtils.findAnnotation(clazz, DynamicDS.class); if (targetDataSource != null) { DataSourceContextHolder.setTargetDataSource(DataSourceEnum.valueOf(targetDataSource.value())); } else { DataSourceContextHolder.resetDefaultDataSource(); } result = joinPoint.proceed(); return result; } catch (Throwable ex) { throw new RuntimeException(ex); } }
@ExceptionHandler(value = Exception.class) public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { logger.error("[URL] : {}", req.getRequestURL(), e); // If the exception is annotated with @ResponseStatus rethrow it and let // the framework handle it - like the OrderNotFoundException example // at the start of this post. // AnnotationUtils is a Spring Framework utility class. if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) throw e; // Otherwise setup and send the user to a default error-view. ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", req.getRequestURL()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav; }
/** * 为@ConfigBean的bean注册它的Factory Method,通过静态Factory Method来创建@ConfigBean实例 * * @param registry * @param beanName * @param beanDefinition */ private void registerFactoryMethodForConfigBean(BeanDefinitionRegistry registry, String beanName, BeanDefinition beanDefinition) { String beanClassName = beanDefinition.getBeanClassName(); if (beanClassName == null) { // 通过注解@Bean声明的bean,beanClassName=null return; } Class<?> beanClass = ClassUtils.resolveClassName(beanClassName, beanFactory.getBeanClassLoader()); ConfigBean config = AnnotationUtils.findAnnotation(beanClass, ConfigBean.class); if (config == null) { return; } // 为配置bean设置factory method String propertyName = config.value(); ConfigBeanConfigUtils.setConfigBeanFactoryMethod(registry, beanName, beanDefinition, propertyName, config.converter()); }
/** * Finds methods for the given annotation * * It first finds all public member methods of the class or interface represented by objClass, * including those inherited from superclasses and superinterfaces. * * It then loops through these methods searching for a single Annotation of annotationType, * traversing its super methods if no annotation can be found on the given method itself. * * @param objClass - the class * @param annotationType - the annotation to find * @return - the List of Method or an empty List */ @SuppressWarnings("rawtypes") public static List<Method> findMethodsByAnnotation(Class objClass, Class<? extends Annotation> annotationType) { List<Method> annotatedMethods = new ArrayList<Method>(); Method[] methods = objClass.getMethods(); for (Method method : methods) { Annotation annot = AnnotationUtils.findAnnotation(method, annotationType); if (annot != null) { //Just to be sure, lets make sure its not a Bridged (Generic) Method Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method); annotatedMethods.add(resolvedMethod); } } return annotatedMethods; }
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { logger.info("Look for Errai Service definitions"); String[] beans = beanFactory.getBeanDefinitionNames(); for (String beanName : beans) { Class<?> beanType = beanFactory.getType(beanName); Service service = AnnotationUtils.findAnnotation(beanType, Service.class); if (service != null) { try { ServiceTypeParser serviceTypeParser = new ServiceTypeParser(beanType); services.add(new ServiceImplementation(serviceTypeParser, beanName)); logger.debug("Found Errai Service definition: beanName=" + beanName + ", beanType=" + beanType); } catch (NotAService e) { logger.warn("Service annotation present but threw NotAServiceException", e); } } } }
private void injectServicesViaAnnotatedSetterMethods(final Object bean, final String beanName) { ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() { public void doWith(Method method) { ServiceReference s = AnnotationUtils.getAnnotation(method, ServiceReference.class); if (s != null && method.getParameterTypes().length == 1) { try { if (logger.isDebugEnabled()) logger.debug("Processing annotation [" + s + "] for [" + bean.getClass().getName() + "." + method.getName() + "()] on bean [" + beanName + "]"); method.invoke(bean, getServiceImporter(s, method, beanName).getObject()); } catch (Exception e) { throw new IllegalArgumentException("Error processing service annotation", e); } } } }); }
/** * Disabled since it doesn't work as we can't proxy final classes. */ public void tstGetServicePropertySetters() throws Exception { OsgiServiceProxyFactoryBean pfb = new OsgiServiceProxyFactoryBean(); Method setter = AnnotatedBean.class.getMethod("setStringType", new Class<?>[] { String.class }); ServiceReference ref = AnnotationUtils.getAnnotation(setter, ServiceReference.class); processor.getServiceProperty(pfb, ref, setter.getParameterTypes()[0], null); Class<?>[] intfs = (Class[]) getPrivateProperty(pfb, "serviceTypes"); assertEquals(intfs[0], String.class); setter = AnnotatedBean.class.getMethod("setIntType", new Class<?>[] { Integer.TYPE }); ref = AnnotationUtils.getAnnotation(setter, ServiceReference.class); pfb = new OsgiServiceProxyFactoryBean(); processor.getServiceProperty(pfb, ref, setter.getParameterTypes()[0], null); intfs = (Class[]) getPrivateProperty(pfb, "serviceTypes"); assertEquals(intfs[0], Integer.TYPE); }
public void testProperMultiCardinality() throws Exception { OsgiServiceCollectionProxyFactoryBean pfb = new OsgiServiceCollectionProxyFactoryBean(); Method setter = AnnotatedBean.class.getMethod("setAnnotatedBeanTypeWithCardinality0_N", new Class<?>[] { List.class }); ServiceReference ref = AnnotationUtils.getAnnotation(setter, ServiceReference.class); processor.getServiceProperty(pfb, ref, setter.getParameterTypes()[0], null); assertFalse(pfb.getAvailability() == Availability.MANDATORY); setter = AnnotatedBean.class.getMethod("setAnnotatedBeanTypeWithCardinality1_N", new Class<?>[] { SortedSet.class }); ref = AnnotationUtils.getAnnotation(setter, ServiceReference.class); pfb = new OsgiServiceCollectionProxyFactoryBean(); processor.getServiceProperty(pfb, ref, setter.getParameterTypes()[0], null); assertTrue(pfb.getAvailability() == Availability.MANDATORY); }
public void testGetServicePropertyClassloader() throws Exception { OsgiServiceProxyFactoryBean pfb = new OsgiServiceProxyFactoryBean(); Method setter = AnnotatedBean.class.getMethod("setAnnotatedBeanTypeWithClassLoaderClient", new Class<?>[] { AnnotatedBean.class }); ServiceReference ref = AnnotationUtils.getAnnotation(setter, ServiceReference.class); processor.getServiceProperty(pfb, ref, setter.getParameterTypes()[0], null); assertEquals(pfb.getImportContextClassLoader(), ImportContextClassLoaderEnum.CLIENT); pfb = new OsgiServiceProxyFactoryBean(); setter = AnnotatedBean.class.getMethod("setAnnotatedBeanTypeWithClassLoaderUmanaged", new Class<?>[] { AnnotatedBean.class }); ref = AnnotationUtils.getAnnotation(setter, ServiceReference.class); processor.getServiceProperty(pfb, ref, setter.getParameterTypes()[0], null); assertEquals(pfb.getImportContextClassLoader(), ImportContextClassLoaderEnum.UNMANAGED); pfb = new OsgiServiceProxyFactoryBean(); setter = AnnotatedBean.class.getMethod("setAnnotatedBeanTypeWithClassLoaderServiceProvider", new Class<?>[] { AnnotatedBean.class }); ref = AnnotationUtils.getAnnotation(setter, ServiceReference.class); processor.getServiceProperty(pfb, ref, setter.getParameterTypes()[0], null); assertEquals(pfb.getImportContextClassLoader(), ImportContextClassLoaderEnum.SERVICE_PROVIDER); }
@ExceptionHandler(Exception.class) public ResponseEntity<ErrorDTO> processRuntimeException(Exception ex) throws Exception { BodyBuilder builder; ErrorDTO errorDTO; ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class); if (responseStatus != null) { builder = ResponseEntity.status(responseStatus.value()); errorDTO = new ErrorDTO("error." + responseStatus.value().value(), responseStatus.reason()); } else { builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR); errorDTO = new ErrorDTO(ErrorConstants.ERR_INTERNAL_SERVER_ERROR, "Internal server error"); } return builder.body(errorDTO); }
/** * Finds operations on an entity * @param entityPath path to the entity * @param anyClass resource clause * @return The operations */ private static Map<String,Pair<ResourceOperation,Method>> findOperations(String entityPath, Class<?> anyClass) { Map<String, Pair<ResourceOperation,Method>> embeds = new HashMap<String, Pair<ResourceOperation,Method>>(); List<Method> annotatedMethods = ResourceInspectorUtil.findMethodsByAnnotation(anyClass, Operation.class); if (annotatedMethods != null && !annotatedMethods.isEmpty()) for (Method annotatedMethod : annotatedMethods) { //validateOperationMethod(annotatedMethod, anyClass); Annotation annot = AnnotationUtils.findAnnotation(annotatedMethod, Operation.class); if (annot != null) { Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(annot); String actionName = String.valueOf(annotAttribs.get("value")); String actionPath = ResourceDictionary.propertyResourceKey(entityPath, actionName); ResourceOperation ro = inspectOperation(anyClass, annotatedMethod, HttpMethod.POST); embeds.put(actionPath, new Pair<ResourceOperation, Method>(ro, annotatedMethod)); } } return embeds; }
@ExceptionHandler(Exception.class) public ResponseEntity<ErrorVM> processException(Exception ex) { log.error(ex.getMessage(), ex); BodyBuilder builder; ErrorVM errorVM; ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class); if (responseStatus != null) { builder = ResponseEntity.status(responseStatus.value()); errorVM = new ErrorVM("error." + responseStatus.value().value(), responseStatus.reason()); } else { builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR); errorVM = new ErrorVM(ErrorConstants.ERR_INTERNAL_SERVER_ERROR, "Internal server error"); } return builder.body(errorVM); }
@DataProvider public Object[][] daoMethodsForTest() { List<Object[]> daoMethodList = new ArrayList<>(); for (SqlSourceDao daoInstance : repositoryList) { Class<? extends SqlSourceDao> unproxiedClass = daoInstance.getUnproxiedClass(); for (Method m : unproxiedClass.getMethods()) { SqlSource annotation = AnnotationUtils.findAnnotation(m, SqlSource.class); if (annotation == null || annotation.skipTest()) { continue; } int parameterCount = m.getParameterCount(); Assert.assertTrue(parameterCount <= 1); daoMethodList.add(new Object[]{m.getName(), daoInstance}); } } return daoMethodList.toArray(new Object[][]{}); }
@Bean(name=AnnotationConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME) @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public AsyncAnnotationBeanPostProcessor asyncAdvisor() { Assert.notNull(this.enableAsync, "@EnableAsync annotation metadata was not injected"); AsyncAnnotationBeanPostProcessor bpp = new AsyncAnnotationBeanPostProcessor(); Class<? extends Annotation> customAsyncAnnotation = enableAsync.getClass("annotation"); if (customAsyncAnnotation != AnnotationUtils.getDefaultValue(EnableAsync.class, "annotation")) { bpp.setAsyncAnnotationType(customAsyncAnnotation); } if (this.executor != null) { bpp.setExecutor(this.executor); } bpp.setProxyTargetClass(this.enableAsync.getBoolean("proxyTargetClass")); bpp.setOrder(this.enableAsync.<Integer>getNumber("order")); return bpp; }
/** * Checks whether the given bean type should be assisted by this * {@code @ControllerAdvice} instance. * @param beanType the type of the bean to check * @see org.springframework.web.bind.annotation.ControllerAdvice * @since 4.0 */ public boolean isApplicableToBeanType(Class<?> beanType) { if(!hasSelectors()) { return true; } else if (beanType != null) { for (Class<?> clazz : this.assignableTypes) { if(ClassUtils.isAssignable(clazz, beanType)) { return true; } } for (Class<? extends Annotation> annotationClass : this.annotations) { if(AnnotationUtils.findAnnotation(beanType, annotationClass) != null) { return true; } } String packageName = beanType.getPackage().getName(); for (Package basePackage : this.basePackages) { if(packageName.startsWith(basePackage.getName())) { return true; } } } return false; }
private void processFields(Object bean, Field[] declaredFields) { for (Field field : declaredFields) { ApolloConfig annotation = AnnotationUtils.getAnnotation(field, ApolloConfig.class); if (annotation == null) { continue; } Preconditions.checkArgument(Config.class.isAssignableFrom(field.getType()), "Invalid type: %s for field: %s, should be Config", field.getType(), field); String namespace = annotation.value(); Config config = ConfigService.getConfig(namespace); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, config); } }
/** * @param paramAnot Annotation * @param resource Class<?> * @param aMethod Method * @return ResourceParameter */ private static ResourceParameter findResourceParameter(Annotation paramAnot, Class<?> resource, Method aMethod) { Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(paramAnot); ResourceParameter.KIND paramKind = (ResourceParameter.KIND) annotAttribs.get("kind"); Class<?> dType = String.class; if (ResourceParameter.KIND.HTTP_BODY_OBJECT.equals(paramKind)) { dType = ResourceInspectorUtil.determineType(resource, aMethod); } return ResourceParameter.valueOf( String.valueOf(annotAttribs.get("name")), String.valueOf(annotAttribs.get("title")), String.valueOf(annotAttribs.get("description")), (Boolean)annotAttribs.get("required"), paramKind, (Boolean)annotAttribs.get("allowMultiple"), dType); }
@Override public void whenNewOperation(ResourceOperation operation, Method aMethod) { Annotation addressableProps = AnnotationUtils.findAnnotation(aMethod, BinaryProperties.class); if (addressableProps != null) { Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(addressableProps); String[] props = (String[]) annotAttribs.get("value"); for (String property : props) { String propKey = ResourceDictionary.propertyResourceKey(entityPath,property); if (!operationGroupedByProperty.containsKey(propKey)) { List<ResourceOperation> ops = new ArrayList<ResourceOperation>(); operationGroupedByProperty.put(propKey, ops); } List<ResourceOperation> operations = operationGroupedByProperty.get(propKey); operations.add(operation); } } else { logger.warn("Resource "+resource.getCanonicalName()+" should declare a @BinaryProperties annotation."); } }
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { try { Class<?> wrapped = AopUtils.getTargetClass(bean); if (!isSpring(wrapped)) { Class<?> declaring = AnnotationUtils.findAnnotationDeclaringClass(Steps.class, wrapped); if (null != declaring) { processStepsBean(beanName, wrapped); } } return bean; } catch (Exception e) { throw new FatalBeanException("unable to processAnnotationContainer @Steps beans", e); } }
@SuppressWarnings( {"rawtypes", "unchecked"}) private <T> T getMergedOrDefaultAnnotationValue(String attribute, Class annotationType, Class<T> targetType) { Annotation annotation = AnnotatedElementUtils.findMergedAnnotation(method, annotationType); if (annotation == null) { return targetType.cast(AnnotationUtils.getDefaultValue(annotationType, attribute)); } return targetType.cast(AnnotationUtils.getValue(annotation, attribute)); }
Annotation findMappingAnnotation(AnnotatedElement element) { Annotation mappingAnnotation = element.getAnnotation(RequestMapping.class); if (mappingAnnotation == null) { mappingAnnotation = element.getAnnotation(GetMapping.class); if (mappingAnnotation == null) { mappingAnnotation = element.getAnnotation(PostMapping.class); if (mappingAnnotation == null) { mappingAnnotation = element.getAnnotation(PutMapping.class); if (mappingAnnotation == null) { mappingAnnotation = element.getAnnotation(DeleteMapping.class); if (mappingAnnotation == null) { mappingAnnotation = element.getAnnotation(PatchMapping.class); } } } } } if (mappingAnnotation == null) { if (element instanceof Method) { Method method = (Method) element; mappingAnnotation = AnnotationUtils.findAnnotation(method, RequestMapping.class); } else { Class<?> clazz = (Class<?>) element; mappingAnnotation = AnnotationUtils.findAnnotation(clazz, RequestMapping.class); } } return mappingAnnotation; }
@Override public void beforeTestMethod(TestContext testContext) throws Exception { FixedClock methodFixedClock = AnnotationUtils.findAnnotation(testContext.getTestMethod(), FixedClock.class); if (methodFixedClock == null) { return; } verifyClassAnnotation(testContext); mockClock(testContext, methodFixedClock); }
private void setMessageHandlers(Object bean, Class<?> clazz) { Class<?>[] clazzs = clazz.getInterfaces(); for (Class<?> typeClazz : clazzs) { if (typeClazz.isAssignableFrom(MessageHandler.class)) { TopicRouter topicRouter = AnnotationUtils.findAnnotation(clazz, TopicRouter.class); // 只注册标注TopicRouter的MessageHandler实例 if (null != topicRouter) { String routerKey = topicRouter.name(); messageHandlers.put(routerKey, (MessageHandler) bean); } } } }
private String getRelativeUrl(Method m) { StringBuilder relativeUrl = new StringBuilder(); // me quedo con la annotation (alguna de la lista) ReflectionUtils.filterRequestMappingAnnontations(m).findFirst().ifPresent(annotation -> { Optional<String[]> value; if (RequestMapping.class.isAssignableFrom(annotation.getClass())) { RequestMapping a = (RequestMapping) annotation; value = Optional.ofNullable(a.path().length == 0 ? a.value() : a.path()); } else { value = Optional.ofNullable((String[]) AnnotationUtils.getValue(annotation)); } value.ifPresent(v -> relativeUrl.append(Arrays.asList((String[]) v).stream().findFirst().orElse(""))); }); return relativeUrl.toString(); }
public void before(final Method method) { // create the web driver final RunWithWebDriver runWithWebDriver = Optional .ofNullable(AnnotationUtils.findAnnotation(testClass, RunWithWebDriver.class)) // .orElseThrow(() -> new AssertionError(String.format( "Test class %s is not annotated with %s to specify which web driver should be used for running.", testClass.getName(), RunWithWebDriver.class.getName()))); final WebDriverFactory webDriverFactory = WebDriverFactoryRegistry.getWebDriverFactory(runWithWebDriver.value()); final Map<String, Object> options = Arrays.stream(runWithWebDriver.options()) // .collect(Collectors.toMap(Option::key, Option::value)); webDriver = webDriverFactory.create(options); // inject the entry point final WebDriverEntryPoint entryPoint = Optional.ofNullable(AnnotationUtils.findAnnotation(testClass, WebDriverEntryPoint.class)) // .orElseThrow(() -> new AssertionError(String.format( "Test class %s is not annotated with %s to specify the entry point of the test.", testClass.getName(), WebDriverEntryPoint.class.getName()))); webDriver.get(entryPoint.value()); // setup screenshots Optional.ofNullable(AnnotationUtils.findAnnotation(testClass, TakeScreenshots.class)) // .ifPresent(takeScreenshots -> { screenshots = new Screenshots(webDriver, takeScreenshots, getClass()); try { screenshots.start(method.getName()); } catch (final AssertionError assertionError) { after(method, true, assertionError); throw assertionError; } }); }
private static <A extends Annotation> AspectJAnnotation<A> findAnnotation(Method method, Class<A> toLookFor) { A result = AnnotationUtils.findAnnotation(method, toLookFor); if (result != null) { return new AspectJAnnotation<A>(result); } else { return null; } }
/** * Find annotation related to method intercepted by joinPoint. * * Annotation is searched on method level at first and then if not found on class lever as well. * * Method uses spring {@link AnnotationUtils} findAnnotation(), so it is search for annotation by class hierarchy. * * @param joinPoint join point * @return Optional value of type @{@link LoggingAspectConfig} * @see AnnotationUtils */ public static Optional<LoggingAspectConfig> getConfigAnnotation(JoinPoint joinPoint) { Optional<Method> method = getCallingMethod(joinPoint); Optional<LoggingAspectConfig> result = method .map(m -> AnnotationUtils.findAnnotation(m, LoggingAspectConfig.class)); if (!result.isPresent()) { Optional<Class> clazz = getDeclaringClass(joinPoint); result = clazz.map(aClass -> AnnotationUtils.getAnnotation(aClass, LoggingAspectConfig.class)); } return result; }
private static LepKey getBaseLepKey(LepService typeLepService, LogicExtensionPoint methodLep, Method method) { Map<String, Object> lepServiceAttrs = AnnotationUtils.getAnnotationAttributes(typeLepService); String globalGroupName = (String) lepServiceAttrs.get("group"); String groupName; String keyName; if (methodLep == null) { groupName = globalGroupName; keyName = method.getName(); } else { Map<String, Object> lepAttrs = AnnotationUtils.getAnnotationAttributes(methodLep); String lepGroupName = (String) lepAttrs.get("group"); groupName = (StringUtils.isEmpty(lepGroupName) || lepGroupName.trim().isEmpty()) ? globalGroupName : lepGroupName; keyName = (String) lepAttrs.get("value"); } if (keyName != null && keyName.contains(XmLepConstants.EXTENSION_KEY_SEPARATOR)) { throw new IllegalArgumentException("Key name '" + keyName + "' can't contains segments separator: '" + XmLepConstants.EXTENSION_KEY_SEPARATOR + "'"); } String segments = groupName + XmLepConstants.EXTENSION_KEY_SEPARATOR + keyName; // create Lep key instance return new SeparatorSegmentedLepKey(segments, XmLepConstants.EXTENSION_KEY_SEPARATOR, XmLepConstants.EXTENSION_KEY_GROUP_MODE); }