private static ResolvableType resolveVariable(TypeVariable<?> typeVariable, ResolvableType contextType) { ResolvableType resolvedType; if (contextType.hasGenerics()) { resolvedType = ResolvableType.forType(typeVariable, contextType); if (resolvedType.resolve() != null) { return resolvedType; } } ResolvableType superType = contextType.getSuperType(); if (superType != ResolvableType.NONE) { resolvedType = resolveVariable(typeVariable, superType); if (resolvedType.resolve() != null) { return resolvedType; } } for (ResolvableType ifc : contextType.getInterfaces()) { resolvedType = resolveVariable(typeVariable, ifc); if (resolvedType.resolve() != null) { return resolvedType; } } return ResolvableType.NONE; }
@SuppressWarnings("unchecked") public ServiceInfoPropertySourceAdapter() { Cloud cloud; try { cloud = new CloudFactory().getCloud(); } catch (CloudException e) { // not running on a known cloud environment, so nothing to do cloud = null; } this.cloud = cloud; this.serviceInfoType = (Class) ResolvableType.forClass(getClass()).getSuperType() .getGeneric(0).getRawClass(); }
@Override @SuppressWarnings({ "unchecked", "rawtypes" }) public void multicastEvent(ApplicationEvent event, ResolvableType eventType) { ResolvableType type = eventType == null ? ResolvableType.forInstance(event) : eventType; Collection<ApplicationListener<?>> listeners = getApplicationListeners(event, type); if (listeners.isEmpty()) { return; } List<ApplicationListener<?>> transactionalListeners = listeners.stream()// .filter(PersistentApplicationEventMulticaster::isTransactionalApplicationEventListener)// .collect(Collectors.toList()); if (!transactionalListeners.isEmpty()) { Object eventToPersist = getEventToPersist(event); registry.getObject().store(eventToPersist, transactionalListeners); // EventStore.persist(eventThis) // SpringMVC Controller Atom Feed } for (ApplicationListener listener : listeners) { listener.onApplicationEvent(event); } }
@Override protected void registerBeans(InjectLock annotation, ResolvableType targetType, BeanDefinitionRegistry registry) { String name = LockBean.class.getName() + "-" + annotation.name() + "--" + annotation.name(); if (!registry.containsBeanDefinition(name)) { AbstractBeanDefinition def = BeanDefinitionBuilder.rootBeanDefinition(LockBean.class) .setLazyInit(true) .addPropertyValue("region", annotation.region()) .addPropertyValue("name", annotation.name()) .getBeanDefinition(); AutowireCandidateQualifier qualifier = new AutowireCandidateQualifier(annotation.annotationType()); qualifier.addMetadataAttribute(new BeanMetadataAttribute("region", annotation.region())); qualifier.addMetadataAttribute(new BeanMetadataAttribute("name", annotation.name())); def.addQualifier(qualifier); registry.registerBeanDefinition(name, def); } }
protected ResolvableType getReturnTypeForFactoryMethod(RootBeanDefinition rbd, DependencyDescriptor descriptor) { // Should typically be set for any kind of factory method, since the BeanFactory // pre-resolves them before reaching out to the AutowireCandidateResolver... Class<?> preResolved = rbd.resolvedFactoryMethodReturnType; if (preResolved != null) { return ResolvableType.forClass(preResolved); } else { Method resolvedFactoryMethod = rbd.getResolvedFactoryMethod(); if (resolvedFactoryMethod != null) { if (descriptor.getDependencyType().isAssignableFrom(resolvedFactoryMethod.getReturnType())) { // Only use factory method metadata if the return type is actually expressive enough // for our dependency. Otherwise, the returned instance type may have matched instead // in case of a singleton instance having been registered with the container already. return ResolvableType.forMethodReturnType(resolvedFactoryMethod); } } return null; } }
private void buildConvertersMap() { beanFactory.getBeansWithAnnotation(Converted.class).values() .forEach(bean -> { ResolvableType beanType = ResolvableType.forClass(bean.getClass()); Optional<ResolvableType> converterInterface = Arrays.stream(beanType.getInterfaces()) .filter(iface -> iface.resolve().isAssignableFrom(TypedEventConverter.class)) .findAny(); if (converterInterface.isPresent()) { ResolvableType genericType = converterInterface.get().getGeneric(0); if (genericType.equals(ResolvableType.NONE)) throw new RuntimeException("TypedEventConverter must be generified with an event type"); typedConverters.put(genericType.getRawClass(), (TypedEventConverter) bean); } else { throw new RuntimeException( "Beans annotated with @Converted must implement TypedEventConverter" ); } }); }
/** * Parses a simple value * * @param value the value * @param type the value type * @return parsed result */ private Object parseValue(final Object value, final ResolvableType type) { Object returnVar = null; if (isTypeStandard(type.getRawClass())) { returnVar = value; } else if (isValueCSVDatabaseIndexes(type)) { returnVar = parseCSVDatabaseIndexes(value.toString(), type.getGeneric(0).getRawClass()); } else if (isValueDateTime(value, type)) { returnVar = parseDateTime(value); } else if (isValueDatabaseIndex(type)) { returnVar = parseDatabaseIndex(value.toString(), type.getRawClass()); } else if (isValuePeriod(type)) { returnVar = parsePeriod(value.toString()); } else if (isValueEnum(type)) { returnVar = parseEnum(value.toString(), type.getRawClass()); } return returnVar; }
private static FlowTxExecutor.FlowTxOperateExecutor parseFlowTxOperate(Method method) { logger.debug("解析流程事务方法:{}", method); // 校验方法类型 if (!Modifier.isPublic(method.getModifiers())) { throw new IllegalArgumentException("流程事务方法" + ClassUtils.getQualifiedMethodName(method) + "必须是public类型"); } // 校验入参 Class[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length != 1) { throw new IllegalArgumentException("流程事务方法" + ClassUtils.getQualifiedMethodName(method) + "的入参必须是(TargetContext)"); } if (parameterTypes[0] != TargetContext.class) { throw new IllegalArgumentException("流程事务方法" + ClassUtils.getQualifiedMethodName(method) + "的入参必须是(TargetContext)"); } // 获取目标对象类型 ResolvableType resolvableType = ResolvableType.forMethodParameter(method, 0); Class classOfTarget = resolvableType.getGeneric(0).resolve(Object.class); // 校验返回参数 if (method.getReturnType() != classOfTarget) { throw new IllegalArgumentException("流程事务方法" + ClassUtils.getQualifiedMethodName(method) + "的返回类型必须是目标对象类型"); } return new FlowTxExecutor.FlowTxOperateExecutor(method, classOfTarget); }
/** * 解析处理器方法 */ private static ProcessorMethodExecutor parseProcessorMethod(Class clazz, Method method) { logger.debug("解析处理器方法:{}", method); // 校验方法类型 if (!Modifier.isPublic(method.getModifiers())) { throw new IllegalArgumentException("处理器方法" + ClassUtils.getQualifiedMethodName(method) + "必须是public类型"); } // 校验入参 Class[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length != 1) { throw new IllegalArgumentException("处理器方法" + ClassUtils.getQualifiedMethodName(method) + "入参必须是(TargetContext)"); } if (parameterTypes[0] != TargetContext.class) { throw new IllegalArgumentException("处理器方法" + ClassUtils.getQualifiedMethodName(method) + "入参必须是(TargetContext)"); } // 校验返回类型 if (clazz != ProcessorExecute.class && method.getReturnType() != void.class) { throw new IllegalArgumentException("非@ProcessorExecute类型的处理器方法" + ClassUtils.getQualifiedMethodName(method) + "的返回类型必须是void"); } // 获取目标对象类型 ResolvableType resolvableType = ResolvableType.forMethodParameter(method, 0); Class classOfTarget = resolvableType.getGeneric(0).resolve(Object.class); return new ProcessorMethodExecutor(method, classOfTarget); }
@Bean @Scope(scopeName = "prototype") @SuppressWarnings("unchecked") public <ITEM> Grid<ITEM> configureBeanGrid(DependencyDescriptor dependencyDescriptor) { logger.debug("Configuring Vaadin Grid as bean"); long timestamp = System.currentTimeMillis(); ResolvableType injectionPointType = dependencyDescriptor.getResolvableType(); if (!injectionPointType.hasGenerics()) { throw new IllegalStateException("Grid injection point is expected to declare a static item type"); } ResolvableType genericType = injectionPointType.getGeneric(); Class<ITEM> itemType = (Class<ITEM>) genericType.resolve(); logger.debug("Vaadin Grid will use " + itemType.getCanonicalName() + " as item type"); Grid<ITEM> grid = configureGridInstance(itemType); long configTime = System.currentTimeMillis() - timestamp; logger.debug("Done configuring Grid for " + itemType.getName() + " in " + configTime + "ms"); return grid; }
@SuppressWarnings("unchecked") private <PROPERTY_TYPE> BeanGridValueProvider<PROPERTY_TYPE> findValueProvider(Class<PROPERTY_TYPE> propertyType) { if (Number.class.isAssignableFrom(propertyType)) { propertyType = (Class<PROPERTY_TYPE>) Number.class; } ResolvableType valueProviderType = ResolvableType.forClassWithGenerics(BeanGridValueProvider.class, propertyType); List<String> valueProviderNames = Arrays.asList(appContext.getBeanNamesForType(valueProviderType)); if (valueProviderNames.isEmpty()) { return (BeanGridValueProvider<PROPERTY_TYPE>) appContext.getBean(BeanGridDefaultValueProvider.class); } if (valueProviderNames.size() == 1) { return appContext.getBean(valueProviderNames.iterator().next(), BeanGridValueProvider.class); } throw new ColumnDefinitionException("Could not find unique " + BeanGridValueProvider.class.getSimpleName() + " for type " + propertyType.getSimpleName()); }
@Override public void init(Method listenMethod) { ConfigListener configListenerAnnotation = AnnotatedElementUtils.findMergedAnnotation(listenMethod.getDeclaringClass(), ConfigListener.class); if (configListenerAnnotation == null) { throw new IllegalArgumentException("@ListenConfigModified只能标注在配置监听器(@ConfigListener)的方法上"); } // 校验入参 Class[] parameterTypes = listenMethod.getParameterTypes(); if (parameterTypes.length != 1) { throw new RuntimeException("监听配置被修改方法" + ClassUtils.getQualifiedMethodName(listenMethod) + "的入参必须是(List<ModifiedProperty>)"); } if (parameterTypes[0] != List.class) { throw new RuntimeException("监听配置被修改方法" + ClassUtils.getQualifiedMethodName(listenMethod) + "的入参必须是(List<ModifiedProperty>)"); } ResolvableType resolvableType = ResolvableType.forMethodParameter(listenMethod, 0); if (resolvableType.getGeneric(0).resolve(Object.class) != ModifiedProperty.class) { throw new RuntimeException("监听配置被修改方法" + ClassUtils.getQualifiedMethodName(listenMethod) + "的入参必须是(List<ModifiedProperty>)"); } // 设置事件类型 ListenConfigModified listenConfigModifiedAnnotation = AnnotatedElementUtils.findMergedAnnotation(listenMethod, ListenConfigModified.class); eventType = new ConfigModifiedEventType(configListenerAnnotation.configContextName(), listenConfigModifiedAnnotation.prefix()); }
/** * Resolve the method arguments to use for the specified {@link ApplicationEvent}. * <p>These arguments will be used to invoke the method handled by this instance. Can * return {@code null} to indicate that no suitable arguments could be resolved and * therefore the method should not be invoked at all for the specified event. */ protected Object[] resolveArguments(ApplicationEvent event) { ResolvableType declaredEventType = getResolvableType(event); if (declaredEventType == null) { return null; } if (this.method.getParameterTypes().length == 0) { return new Object[0]; } if (!ApplicationEvent.class.isAssignableFrom(declaredEventType.getRawClass()) && event instanceof PayloadApplicationEvent) { return new Object[] {((PayloadApplicationEvent) event).getPayload()}; } else { return new Object[] {event}; } }
private List<ResolvableType> resolveDeclaredEventTypes() { int count = this.method.getParameterTypes().length; if (count > 1) { throw new IllegalStateException( "Maximum one parameter is allowed for event listener method: " + this.method); } EventListener ann = getEventListener(); if (ann != null && ann.classes().length > 0) { List<ResolvableType> types = new ArrayList<ResolvableType>(); for (Class<?> eventType : ann.classes()) { types.add(ResolvableType.forClass(eventType)); } return types; } else { if (count == 0) { throw new IllegalStateException( "Event parameter is mandatory for event listener method: " + this.method); } return Collections.singletonList(ResolvableType.forMethodParameter(this.method, 0)); } }
private void multicastEvent(boolean match, Class<?> listenerType, ApplicationEvent event, ResolvableType eventType) { @SuppressWarnings("unchecked") ApplicationListener<ApplicationEvent> listener = (ApplicationListener<ApplicationEvent>) mock(listenerType); SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster(); smc.addApplicationListener(listener); if (eventType != null) { smc.multicastEvent(event, eventType); } else { smc.multicastEvent(event); } int invocation = match ? 1 : 0; verify(listener, times(invocation)).onApplicationEvent(event); }
protected List<ResolvableType> resolveDeclaredEventTypes(Method method, EventListener ann) { int count = method.getParameterTypes().length; if (count > 1) { throw new IllegalStateException( "Maximum one parameter is allowed for event listener method: " + method); } if (ann != null && ann.classes().length > 0) { List<ResolvableType> types = new ArrayList<>(ann.classes().length); for (Class<?> eventType : ann.classes()) { types.add(ResolvableType.forClass(eventType)); } return types; } else { if (count == 0) { throw new IllegalStateException( "Event parameter is mandatory for event listener method: " + method); } return Collections.singletonList(ResolvableType.forMethodParameter(method, 0)); } }
/** * Get all bean names for the given type, including those defined in ancestor * factories. Will return unique names in case of overridden bean definitions. * <p>Does consider objects created by FactoryBeans, which means that FactoryBeans * will get initialized. If the object created by the FactoryBean doesn't match, * the raw FactoryBean itself will be matched against the type. * <p>This version of {@code beanNamesForTypeIncludingAncestors} automatically * includes prototypes and FactoryBeans. * @param lbf the bean factory * @param type the type that beans must match (as a {@code ResolvableType}) * @return the array of matching bean names, or an empty array if none * @since 4.2 */ public static String[] beanNamesForTypeIncludingAncestors(ListableBeanFactory lbf, ResolvableType type) { Assert.notNull(lbf, "ListableBeanFactory must not be null"); String[] result = lbf.getBeanNamesForType(type); if (lbf instanceof HierarchicalBeanFactory) { HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { String[] parentResult = beanNamesForTypeIncludingAncestors( (ListableBeanFactory) hbf.getParentBeanFactory(), type); List<String> resultList = new ArrayList<String>(); resultList.addAll(Arrays.asList(result)); for (String beanName : parentResult) { if (!resultList.contains(beanName) && !hbf.containsLocalBean(beanName)) { resultList.add(beanName); } } result = StringUtils.toStringArray(resultList); } } return result; }
private static Type getType(Type type, Class<?> contextClass) { if (contextClass != null) { ResolvableType resolvedType = ResolvableType.forType(type); if (type instanceof TypeVariable) { ResolvableType resolvedTypeVariable = resolveVariable((TypeVariable) type, ResolvableType.forClass(contextClass)); if (resolvedTypeVariable != ResolvableType.NONE) { return resolvedTypeVariable.resolve(); } } else if (type instanceof ParameterizedType && resolvedType.hasUnresolvableGenerics()) { ParameterizedType parameterizedType = (ParameterizedType) type; Class<?>[] generics = new Class[parameterizedType.getActualTypeArguments().length]; Type[] typeArguments = parameterizedType.getActualTypeArguments(); for (int i = 0; i < typeArguments.length; ++i) { Type typeArgument = typeArguments[i]; if (typeArgument instanceof TypeVariable) { ResolvableType resolvedTypeArgument = resolveVariable((TypeVariable) typeArgument, ResolvableType.forClass(contextClass)); if (resolvedTypeArgument != ResolvableType.NONE) { generics[i] = resolvedTypeArgument.resolve(); } else { generics[i] = ResolvableType.forType(typeArgument).resolve(); } } else { generics[i] = ResolvableType.forType(typeArgument).resolve(); } } return ResolvableType.forClassWithGenerics(resolvedType.getRawClass(), generics).getType(); } } return type; }
public ResolvableType getActualType(ResolvableType original){ if(!original.hasGenerics()){ return original; }else{ return original.getGeneric(0); } }
public ServiceMethodInfo(Method method) { this.method = method; ReactiveSocket annotated = AnnotatedElementUtils.findMergedAnnotation(method, ReactiveSocket.class); if(annotated == null){ throw new IllegalStateException("Service methods must be annotated with a one of {@OneWayMapping, @RequestOneMapping, @RequestManyMapping, @RequestStreamMapping} "); } this.mappingInfo = new ServiceMappingInfo(annotated.value(), annotated.mimeType(), annotated.exchangeMode()); this.returnType = ResolvableType.forMethodReturnType(method); findPayloadParameter(); validate(); }
public static Class<?> getActualType(ResolvableType type){ if(Publisher.class.isAssignableFrom(type.resolve())){ return type.getGeneric(0).resolve(); }else{ return type.resolve(); } }
@Override protected void registerBeans(InjectRpcClient annotation, ResolvableType targetType, BeanDefinitionRegistry registry) { String tag = annotation.tag().isEmpty() ? "" : '#' + annotation.tag(); String name = RpcClientBean.class.getName() + tag + "-" + targetType.toString(); if (!registry.containsBeanDefinition(name)) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(RpcClientBean.class) .setLazyInit(true) .addPropertyValue("rpcInterface", targetType.getType().getTypeName()); if (!annotation.tag().isEmpty()) { builder.addPropertyValue("tag", annotation.tag()); } AbstractBeanDefinition def = builder.getBeanDefinition(); AutowireCandidateQualifier qualifier = new AutowireCandidateQualifier(annotation.annotationType()); if (!annotation.tag().isEmpty()) { qualifier.setAttribute("tag", annotation.tag()); } def.addQualifier(qualifier); registry.registerBeanDefinition(name, def); } }
@Override protected void registerBeans(InjectConnector annotation, ResolvableType targetType, BeanDefinitionRegistry registry) { String name = NetworkConnectorBean.class.getName() + "-" + annotation.value(); if (!registry.containsBeanDefinition(name)) { AbstractBeanDefinition def = BeanDefinitionBuilder.rootBeanDefinition(NetworkConnectorBean.class) .setLazyInit(true) .addPropertyValue("protocol", annotation.value()) .getBeanDefinition(); def.addQualifier(new AutowireCandidateQualifier(annotation.annotationType(), annotation.value())); registry.registerBeanDefinition(name, def); } }
@Override protected void registerBeans(InjectCounter annotation, ResolvableType targetType, BeanDefinitionRegistry registry) { String name = CounterMetricBean.class.getName() + "-" + annotation.value(); if (!registry.containsBeanDefinition(name)) { AbstractBeanDefinition def = BeanDefinitionBuilder.rootBeanDefinition(CounterMetricBean.class) .setLazyInit(true) .addPropertyValue("name", annotation.value()) .getBeanDefinition(); def.addQualifier(new AutowireCandidateQualifier(annotation.annotationType(), annotation.value())); registry.registerBeanDefinition(name, def); } }
@Override protected void registerBeans(InjectMetric annotation, ResolvableType targetType, BeanDefinitionRegistry registry) { String name = MetricBean.class.getName() + "-" + annotation.value(); if (!registry.containsBeanDefinition(name)) { AbstractBeanDefinition def = BeanDefinitionBuilder.rootBeanDefinition(MetricBean.class) .setLazyInit(true) .addPropertyValue("name", annotation.value()) .getBeanDefinition(); def.addQualifier(new AutowireCandidateQualifier(annotation.annotationType(), annotation.value())); registry.registerBeanDefinition(name, def); } }
@Override protected void registerBeans(InjectLockRegion annotation, ResolvableType targetType, BeanDefinitionRegistry registry) { String name = LockRegionBean.class.getName() + "-" + annotation.value(); if (!registry.containsBeanDefinition(name)) { AbstractBeanDefinition def = BeanDefinitionBuilder.rootBeanDefinition(LockRegionBean.class) .setLazyInit(true) .addPropertyValue("region", annotation.value()) .getBeanDefinition(); def.addQualifier(new AutowireCandidateQualifier(annotation.annotationType(), annotation.value())); registry.registerBeanDefinition(name, def); } }
@Override protected void registerBeans(InjectChannel annotation, ResolvableType targetType, BeanDefinitionRegistry registry) { String name = MessagingChannelBean.class.getName() + "-" + annotation.value(); if (!registry.containsBeanDefinition(name)) { AbstractBeanDefinition def = BeanDefinitionBuilder.rootBeanDefinition(MessagingChannelBean.class) .setLazyInit(true) .addPropertyValue("channel", annotation.value()) .getBeanDefinition(); def.addQualifier(new AutowireCandidateQualifier(annotation.annotationType(), annotation.value())); registry.registerBeanDefinition(name, def); } }
private Class<?> getConfigurationClassFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition, String name) throws Exception { Method method = getFactoryMethod(beanFactory, definition); Class<?> generic = ResolvableType.forMethodReturnType(method).as(FactoryBean.class).resolveGeneric(); if ((generic == null || generic.equals(Object.class)) && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { generic = getTypeFromAttribute(definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); } return generic; }
private Class<?> getDirectFactoryBeanGeneric( ConfigurableListableBeanFactory beanFactory, BeanDefinition definition, String name) throws ClassNotFoundException, LinkageError { Class<?> factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(), beanFactory.getBeanClassLoader()); Class<?> generic = ResolvableType.forClass(factoryBeanClass).as(FactoryBean.class).resolveGeneric(); if ((generic == null || generic.equals(Object.class)) && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { generic = getTypeFromAttribute(definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); } return generic; }
/** * Write normal value to entity. * * @param accessor The accessor for the existing entity * @param key The fields name we are overwriting * @param value The new value */ private void writeValueToEntity(final PropertyAccessor accessor, final String key, final Object value) { final ResolvableType type = accessor.getPropertyTypeDescriptor(key).getResolvableType(); accessor.setPropertyValue(key, parseValue(value, type)); }
/** * processes an array map * * @param value value to process * @param type type of this array * @return new list * @throws JSONException the exception */ private Object parseArrayMap(final JSONObject value, final ResolvableType type) throws JSONException { final JSONArray newArray = new JSONArray(); JSONUtil.loopObjectData(value, (key, data) -> { if (NumberUtils.isCreatable(key)) { newArray.put(data); } }); return parseArray(newArray, type); }
private static ServicePhaseExecutor parseServicePhase(Method method) { logger.debug("解析服务方法:{}", method); // 校验方法类型 if (!Modifier.isPublic(method.getModifiers())) { throw new IllegalArgumentException("服务方法" + ClassUtils.getQualifiedMethodName(method) + "必须是public类型"); } // 校验入参 Class[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length != 1 || parameterTypes[0] != ServiceContext.class) { throw new IllegalArgumentException("服务方法" + ClassUtils.getQualifiedMethodName(method) + "的入参必须是(ServiceContext)"); } // 校验返回类型 if (method.getReturnType() != void.class) { throw new IllegalArgumentException("服务方法" + ClassUtils.getQualifiedMethodName(method) + "的返回类型必须是void"); } // 获取ServiceContext中泛型O、R的真实类型 ResolvableType resolvableType = ResolvableType.forMethodParameter(method, 0); Class orderClass = resolvableType.getGeneric(0).resolve(Object.class); Class resultClass = resolvableType.getGeneric(1).resolve(Object.class); // 校验result是否有默认构造函数 if (method.isAnnotationPresent(ServiceExecute.class)) { if (!ClassUtils.hasConstructor(resultClass, new Class[]{})) { throw new IllegalArgumentException("@ServiceExecute服务方法" + ClassUtils.getQualifiedMethodName(method) + "参数ServiceContext的泛型" + ClassUtils.getShortName(resultClass) + "必须得有默认构造函数"); } } return new ServicePhaseExecutor(method, orderClass, resultClass); }
@Bean public CommandLineRunner myCommandLineRunner() { return args -> { String api = "http://stockmarket.streamdata.io/prices"; String token = "[YOUR TOKEN HERE]"; // If ever you want to pass some headers to your API // specify a header map associated with the request Map<String,String> headers = new HashMap<>(); // add this header if you wish to stream Json rather than Json-patch // NOTE: no 'patch' event will be emitted. // headers.put("Accept", "application/json"); URI streamdataUri = streamdataUri(api, token, headers); // source: https://github.com/spring-projects/spring-framework/blob/v5.0.0.RC1/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SseIntegrationTests.java ResolvableType type = forClassWithGenerics(ServerSentEvent.class, JsonNode.class); // Create the web client and the flux of events WebClient client = WebClient.create(); Flux<ServerSentEvent<JsonNode>> events = client.get() .uri(streamdataUri) .accept(TEXT_EVENT_STREAM) .exchange() .flatMapMany(response -> response.body(toFlux(type))); // use of a transformer to apply the patches events.as(new PatchTransformer()) // Subscribe to the flux with a consumer that applies patches .subscribe(System.out::println, Throwable::printStackTrace); // Add a block here because CommandLineRunner returns after the execution of the code // ... and make the code run 1 day. Mono.just("That's the end!") .delayElement(Duration.ofDays(1)) .block(); }; }
@Override public Object process(Mono<ClientResponse> monoResponse, ResolvableType bodyType) { if (isMono(bodyType)) { return toMono(monoResponse, bodyType.getGeneric(0).getRawClass()); } else if (isFlux(bodyType)) { return toFlux(monoResponse, bodyType.getGeneric(0).getRawClass()); } else if (isVoid(bodyType)) { return toVoid(monoResponse); } else { return toObject(monoResponse, bodyType.getRawClass()); } }
public Builder body(Integer bodyIndex, Type bodyType) { if (this.bodyType != null && this.bodyIndex != null) { throw new IllegalArgumentException(); } this.bodyIndex = bodyIndex; this.bodyType = ResolvableType.forType(bodyType); return this; }
@SuppressWarnings("unchecked") protected <TYPE> Summarizer<TYPE> getSummarizerFor(ColumnDefinition definition) { Class<? extends Summarizer<TYPE>> summarizerType = null; String summarizerBeanName = null; ResolvableType resolvableSummarizerType = ResolvableType.forClassWithGenerics(Summarizer.class, definition.getPropertyType()); List<String> availableSummarizerBeanNames = Arrays .asList(appContext.getBeanNamesForType(resolvableSummarizerType)); if (availableSummarizerBeanNames.isEmpty()) { throw new ColumnDefinitionException( "No summarizer available for property type " + definition.getPropertyType().getSimpleName() + "."); } else if (availableSummarizerBeanNames.size() > 1) { throw new ColumnDefinitionException("There are more than one summarizer available for property type " + definition.getPropertyType().getSimpleName() + ": " + availableSummarizerBeanNames.stream().collect(Collectors.joining(", "))); } summarizerBeanName = availableSummarizerBeanNames.iterator().next(); summarizerType = (Class<? extends Summarizer<TYPE>>) appContext.getType(summarizerBeanName); if (summarizerType == null) { throw new ColumnDefinitionException("Could not determine type of the summarizer for column " + definition.getPropertyName() + " with type " + definition.getPropertyType().getSimpleName()); } return appContext.getBean(summarizerBeanName, summarizerType); }
@PostConstruct @SuppressWarnings("unchecked") protected void initialize() { ResolvableType converterResolvable = ResolvableType.forClassWithGenerics(ConverterBean.class, String.class, propertyType); String converterBeanName = Arrays.asList(appContext.getBeanNamesForType(converterResolvable)).iterator().next(); converter = appContext.getBean(converterBeanName, ConverterBean.class); }