List of usage examples for org.springframework.util Assert isInstanceOf
public static void isInstanceOf(Class<?> type, @Nullable Object obj, Supplier<String> messageSupplier)
From source file:org.emonocot.harvest.common.MultiResourceDeletingTasklet.java
/** * <p>//from www. ja va 2 s .c o m * Vrifie que l'attribut resources est bien valoris et que ses lments * correspondent des FileSystemResource. * </p> * */ public final void afterPropertiesSet() { Assert.notNull(resources, "resources must be set"); for (Resource lResource : resources) { Assert.isInstanceOf(FileSystemResource.class, lResource, "The attribute 'resources' does not contain" + " resources of the type FileSystemResource."); } }
From source file:org.geoserver.security.ldap.GeoserverLdapBindAuthenticator.java
/** * If userFilter is defined we extract user data using the filter and * dnPattern (if defined) to transform username for authentication. * //from w w w. j a v a2s .co m * @param authentication * @return */ protected DirContextOperations authenticateUsingFilter(Authentication authentication) { DirContextOperations user = null; Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects"); String username = authentication.getName(); String password = (String) authentication.getCredentials(); // format given username if required if (userFormat != null && !userFormat.equals("")) { username = MessageFormat.format(userFormat, username); } if (!StringUtils.hasLength(password)) { logger.debug("Rejecting empty password for user " + username); throw new BadCredentialsException( messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password")); } DirContext ctx = null; String userDnStr = ""; try { ctx = getContextSource().getContext(username, password); // Check for password policy control PasswordPolicyControl ppolicy = PasswordPolicyControlExtractor.extractControl(ctx); logger.debug("Retrieving user object using filter..."); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); user = SpringSecurityLdapTemplate.searchForSingleEntryInternal(ctx, searchCtls, "", userFilter, new Object[] { username }); userDnStr = user.getDn().toString(); if (ppolicy != null) { user.setAttributeValue(ppolicy.getID(), ppolicy); } } catch (NamingException e) { // This will be thrown if an invalid user name is used and the // method may // be called multiple times to try different names, so we trap the // exception // unless a subclass wishes to implement more specialized behaviour. if ((e instanceof org.springframework.ldap.AuthenticationException) || (e instanceof org.springframework.ldap.OperationNotSupportedException)) { handleBindException(userDnStr, username, e); } else { throw e; } } catch (javax.naming.NamingException e) { throw LdapUtils.convertLdapException(e); } finally { LdapUtils.closeContext(ctx); } if (user == null) { throw new BadCredentialsException( messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials")); } return user; }
From source file:org.jasig.cas.ticket.registry.support.BatchedTicketRegistryCleaner.java
@PostConstruct public void init() { Assert.isInstanceOf(BatchableTicketRegistry.class, ticketRegistry, "ticketRegistry must be of type BatchableTicketRegistry"); }
From source file:org.openspaces.core.space.cache.AbstractLocalCacheSpaceFactoryBean.java
protected void validate() { Assert.notNull(space, "space property must be set"); Assert.isInstanceOf(IDirectSpaceProxy.class, space, "unsupported space proxy class: " + space.getClass().getName()); }
From source file:org.springframework.batch.item.xml.StaxUtils.java
public static Source getSource(XMLEventReader r) throws Exception { if (hasSpring30StaxSupport) { // org.springframework.util.xml.StaxUtils.createStaxSource(r) Object result = staxUtilsSourceMethodOnSpring30.invoke(null, r); Assert.isInstanceOf(Source.class, result, "the result should be assignable to " + Source.class.getName()); return (Source) result; } else if (hasSpringWs15StaxSupport) { Object result = staxSourceClassCtorOnSpringWs15.newInstance(r); Assert.isInstanceOf(Source.class, result, "the result should be assignable to " + Source.class.getName()); return (Source) result; }// w w w . java2 s .c o m // maybe you don't have either environment? return null; }
From source file:org.springframework.batch.item.xml.StaxUtils.java
public static Result getResult(XMLEventWriter w) throws Exception { if (hasSpring30StaxSupport) { Object result = staxUtilsResultMethodOnSpring30.invoke(null, w); Assert.isInstanceOf(Result.class, result, "the result should be assignable to " + Result.class.getName()); return (Result) result; } else if (hasSpringWs15StaxSupport) { Object result = staxResultClassCtorOnSpringWs15.newInstance(w); Assert.isInstanceOf(Result.class, result, "the result should be assignable to " + Result.class.getName()); return (Result) result; }/* ww w . j a v a 2 s . co m*/ // maybe you don't have either environment? return null; }
From source file:org.springframework.boot.SpringApplication.java
/** * Apply any {@link ApplicationContextInitializer}s to the context before it is * refreshed.//w w w. j a va2 s . com * @param context the configured ApplicationContext (not refreshed yet) * @see ConfigurableApplicationContext#refresh() */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected void applyInitializers(ConfigurableApplicationContext context) { for (ApplicationContextInitializer initializer : getInitializers()) { Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class); Assert.isInstanceOf(requiredType, context, "Unable to call initializer."); initializer.initialize(context); } }
From source file:org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.java
@Override public void setBeanFactory(BeanFactory beanFactory) { Assert.isInstanceOf(ListableBeanFactory.class, beanFactory, "WebServerCustomizerBeanPostProcessor can only be used " + "with a ListableBeanFactory"); this.beanFactory = (ListableBeanFactory) beanFactory; }
From source file:org.springframework.cloud.stream.binder.AbstractMessageChannelBinder.java
/** * Binds an outbound channel to a given destination. The implementation delegates to * {@link ProvisioningProvider#provisionProducerDestination(String, ProducerProperties)} * and {@link #createProducerMessageHandler(ProducerDestination, ProducerProperties, MessageChannel)} * for handling the middleware specific logic. If the returned producer message * handler is an {@link InitializingBean} then * {@link InitializingBean#afterPropertiesSet()} will be called on it. Similarly, if * the returned producer message handler endpoint is a {@link Lifecycle}, then * {@link Lifecycle#start()} will be called on it. * * @param destination the name of the destination * @param outputChannel the channel to be bound * @param producerProperties the {@link ProducerProperties} of the binding * @return the Binding for the channel// w w w . j ava 2 s . c o m * @throws BinderException on internal errors during binding */ @Override public final Binding<MessageChannel> doBindProducer(final String destination, MessageChannel outputChannel, final P producerProperties) throws BinderException { Assert.isInstanceOf(SubscribableChannel.class, outputChannel, "Binding is supported only for SubscribableChannel instances"); final MessageHandler producerMessageHandler; final ProducerDestination producerDestination; try { producerDestination = this.provisioningProvider.provisionProducerDestination(destination, producerProperties); SubscribableChannel errorChannel = producerProperties.isErrorChannelEnabled() ? registerErrorInfrastructure(producerDestination) : null; producerMessageHandler = createProducerMessageHandler(producerDestination, producerProperties, errorChannel); if (producerMessageHandler instanceof InitializingBean) { ((InitializingBean) producerMessageHandler).afterPropertiesSet(); } } catch (Exception e) { if (e instanceof BinderException) { throw (BinderException) e; } else if (e instanceof ProvisioningException) { throw (ProvisioningException) e; } else { throw new BinderException("Exception thrown while building outbound endpoint", e); } } if (producerMessageHandler instanceof Lifecycle) { ((Lifecycle) producerMessageHandler).start(); } postProcessOutputChannel(outputChannel, producerProperties); ((SubscribableChannel) outputChannel).subscribe(new SendingHandler(producerMessageHandler, HeaderMode.embeddedHeaders.equals(producerProperties.getHeaderMode()), this.headersToEmbed, producerProperties.isUseNativeEncoding())); return new DefaultBinding<MessageChannel>(destination, null, outputChannel, producerMessageHandler instanceof Lifecycle ? (Lifecycle) producerMessageHandler : null) { @Override public void afterUnbind() { try { destroyErrorInfrastructure(producerDestination); if (producerMessageHandler instanceof DisposableBean) { ((DisposableBean) producerMessageHandler).destroy(); } } catch (Exception e) { AbstractMessageChannelBinder.this.logger.error("Exception thrown while unbinding " + toString(), e); } afterUnbindProducer(producerDestination, producerProperties); } }; }
From source file:org.springframework.cloud.stream.binder.kafka.streams.KafkaStreamsStreamListenerSetupMethodOrchestrator.java
@Override @SuppressWarnings({ "unchecked" }) public Object[] adaptAndRetrieveInboundArguments(Method method, String inboundName, ApplicationContext applicationContext, StreamListenerParameterAdapter... streamListenerParameterAdapters) { Object[] arguments = new Object[method.getParameterTypes().length]; for (int parameterIndex = 0; parameterIndex < arguments.length; parameterIndex++) { MethodParameter methodParameter = MethodParameter.forExecutable(method, parameterIndex); Class<?> parameterType = methodParameter.getParameterType(); Object targetReferenceValue = null; if (methodParameter.hasParameterAnnotation(Input.class)) { targetReferenceValue = AnnotationUtils .getValue(methodParameter.getParameterAnnotation(Input.class)); Input methodAnnotation = methodParameter.getParameterAnnotation(Input.class); inboundName = methodAnnotation.value(); } else if (arguments.length == 1 && StringUtils.hasText(inboundName)) { targetReferenceValue = inboundName; }// w w w. j a v a 2s. c om if (targetReferenceValue != null) { Assert.isInstanceOf(String.class, targetReferenceValue, "Annotation value must be a String"); Object targetBean = applicationContext.getBean((String) targetReferenceValue); BindingProperties bindingProperties = this.bindingServiceProperties .getBindingProperties(inboundName); enableNativeDecodingForKTableAlways(parameterType, bindingProperties); //Retrieve the StreamsConfig created for this method if available. //Otherwise, create the StreamsBuilderFactory and get the underlying config. if (!this.methodStreamsBuilderFactoryBeanMap.containsKey(method)) { buildStreamsBuilderAndRetrieveConfig(method, applicationContext, inboundName); } try { StreamsBuilderFactoryBean streamsBuilderFactoryBean = this.methodStreamsBuilderFactoryBeanMap .get(method); StreamsBuilder streamsBuilder = streamsBuilderFactoryBean.getObject(); KafkaStreamsConsumerProperties extendedConsumerProperties = this.kafkaStreamsExtendedBindingProperties .getExtendedConsumerProperties(inboundName); //get state store spec KafkaStreamsStateStoreProperties spec = buildStateStoreSpec(method); Serde<?> keySerde = this.keyValueSerdeResolver.getInboundKeySerde(extendedConsumerProperties); Serde<?> valueSerde = this.keyValueSerdeResolver .getInboundValueSerde(bindingProperties.getConsumer(), extendedConsumerProperties); final KafkaConsumerProperties.StartOffset startOffset = extendedConsumerProperties .getStartOffset(); Topology.AutoOffsetReset autoOffsetReset = null; if (startOffset != null) { switch (startOffset) { case earliest: autoOffsetReset = Topology.AutoOffsetReset.EARLIEST; break; case latest: autoOffsetReset = Topology.AutoOffsetReset.LATEST; break; default: break; } } if (extendedConsumerProperties.isResetOffsets()) { LOG.warn("Detected resetOffsets configured on binding " + inboundName + ". " + "Setting resetOffsets in Kafka Streams binder does not have any effect."); } if (parameterType.isAssignableFrom(KStream.class)) { KStream<?, ?> stream = getkStream(inboundName, spec, bindingProperties, streamsBuilder, keySerde, valueSerde, autoOffsetReset); KStreamBoundElementFactory.KStreamWrapper kStreamWrapper = (KStreamBoundElementFactory.KStreamWrapper) targetBean; //wrap the proxy created during the initial target type binding with real object (KStream) kStreamWrapper.wrap((KStream<Object, Object>) stream); this.kafkaStreamsBindingInformationCatalogue .addStreamBuilderFactory(streamsBuilderFactoryBean); for (StreamListenerParameterAdapter streamListenerParameterAdapter : streamListenerParameterAdapters) { if (streamListenerParameterAdapter.supports(stream.getClass(), methodParameter)) { arguments[parameterIndex] = streamListenerParameterAdapter.adapt(kStreamWrapper, methodParameter); break; } } if (arguments[parameterIndex] == null && parameterType.isAssignableFrom(stream.getClass())) { arguments[parameterIndex] = stream; } Assert.notNull(arguments[parameterIndex], "Cannot convert argument " + parameterIndex + " of " + method + "from " + stream.getClass() + " to " + parameterType); } else if (parameterType.isAssignableFrom(KTable.class)) { String materializedAs = extendedConsumerProperties.getMaterializedAs(); String bindingDestination = this.bindingServiceProperties .getBindingDestination(inboundName); KTable<?, ?> table = getKTable(streamsBuilder, keySerde, valueSerde, materializedAs, bindingDestination, autoOffsetReset); KTableBoundElementFactory.KTableWrapper kTableWrapper = (KTableBoundElementFactory.KTableWrapper) targetBean; //wrap the proxy created during the initial target type binding with real object (KTable) kTableWrapper.wrap((KTable<Object, Object>) table); this.kafkaStreamsBindingInformationCatalogue .addStreamBuilderFactory(streamsBuilderFactoryBean); arguments[parameterIndex] = table; } else if (parameterType.isAssignableFrom(GlobalKTable.class)) { String materializedAs = extendedConsumerProperties.getMaterializedAs(); String bindingDestination = this.bindingServiceProperties .getBindingDestination(inboundName); GlobalKTable<?, ?> table = getGlobalKTable(streamsBuilder, keySerde, valueSerde, materializedAs, bindingDestination, autoOffsetReset); GlobalKTableBoundElementFactory.GlobalKTableWrapper globalKTableWrapper = (GlobalKTableBoundElementFactory.GlobalKTableWrapper) targetBean; //wrap the proxy created during the initial target type binding with real object (KTable) globalKTableWrapper.wrap((GlobalKTable<Object, Object>) table); this.kafkaStreamsBindingInformationCatalogue .addStreamBuilderFactory(streamsBuilderFactoryBean); arguments[parameterIndex] = table; } } catch (Exception ex) { throw new IllegalStateException(ex); } } else { throw new IllegalStateException(StreamListenerErrorMessages.INVALID_DECLARATIVE_METHOD_PARAMETERS); } } return arguments; }