org.springframework.util.Assert Java Examples

The following examples show how to use org.springframework.util.Assert. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File:    From java-technology-stack with MIT License 6 votes vote down vote up
 * Renders the '{@code input(radio)}' element with the configured
 * {@link #setValue(Object) value}. Marks the element as checked if the
 * value matches the {@link #getValue bound value}.
protected int writeTagContent(TagWriter tagWriter) throws JspException {
	String id = resolveId();
	writeOptionalAttribute(tagWriter, "id", id);
	writeOptionalAttribute(tagWriter, "name", getName());

	Object resolvedLabel = evaluate("label", getLabel());
	if (resolvedLabel != null) {
		Assert.state(id != null, "Label id is required");
		tagWriter.writeAttribute("for", id);

	return SKIP_BODY;
Example #2
Source File:    From foremast with Apache License 2.0 6 votes vote down vote up
 * Find the {@link HandlerMapping} that would handle the given request and
 * return it as a {@link MatchableHandlerMapping} that can be used to test
 * request-matching criteria.
 * <p>If the matching HandlerMapping is not an instance of
 * {@link MatchableHandlerMapping}, an IllegalStateException is raised.
 * @param request the current request
 * @return the resolved matcher, or {@code null}
 * @throws Exception if any of the HandlerMapping's raise an exception
public HandlerExecutionChain getHandlerExecutionChain(HttpServletRequest request) throws Exception {
    Assert.notNull(this.handlerMappings, "Handler mappings not initialized");
    HttpServletRequest wrapper = new RequestAttributeChangeIgnoringWrapper(request);
    for (HandlerMapping handlerMapping : this.handlerMappings) {
        Object handler = handlerMapping.getHandler(wrapper);
        if (handler == null) {
        if (handler instanceof HandlerExecutionChain) {
            return (HandlerExecutionChain)handler;
        throw new IllegalStateException("HandlerMapping is not a MatchableHandlerMapping");
    return null;
Example #3
Source File:    From onetwo with Apache License 2.0 6 votes vote down vote up
private void writeForm(MultiValueMap<String, String> formData, @Nullable MediaType contentType,
		HttpOutputMessage outputMessage) throws IOException {

	contentType = getMediaType(contentType);

	Charset charset = contentType.getCharset();
	Assert.notNull(charset, "No charset"); // should never occur

	final byte[] bytes = serializeForm(formData, charset).getBytes(charset);

	if (outputMessage instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
		streamingOutputMessage.setBody(outputStream -> StreamUtils.copy(bytes, outputStream));
	else {
		StreamUtils.copy(bytes, outputMessage.getBody());
Example #4
Source File:    From java-platform with Apache License 2.0 6 votes vote down vote up
public String getAccessToken(String code) {
	Map<String, Object> parameterMap = new HashMap<>();
	parameterMap.put("grant_type", "authorization_code");
	parameterMap.put("client_id", getClientId());
	parameterMap.put("client_secret", getClientSecret());
	parameterMap.put("code", code);
	parameterMap.put("redirect_uri", getRedirectUri());
	String responseString = get("", parameterMap);

	List<NameValuePair> nameValuePairs = URLEncodedUtils.parse(responseString, Charset.forName("utf-8"));
	Map<String, Object> result = new HashMap<>();
	for (NameValuePair nameValuePair : nameValuePairs) {
		result.put(nameValuePair.getName(), nameValuePair.getValue());

	return getParameter(nameValuePairs, "access_token");
Example #5
Source File:    From xechat with MIT License 6 votes vote down vote up
public void doBefore(JoinPoint joinPoint) {
    log.debug("before -> {}", joinPoint);

    MessageVO messageVO = null;
    Object[] args = joinPoint.getArgs();
    for (Object obj : args) {
        if (obj instanceof MessageVO) {
            messageVO = (MessageVO) obj;

    Assert.notNull(messageVO, "方法必需以MessageVO类或该类的子类作为参数");

    if (messageVO.getType() == MessageTypeEnum.USER) {
        // 对于User类型的消息做敏感词处理

    log.debug("添加聊天记录 -> {}", messageVO);
Example #6
Source File:    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public int deleteMessages( User sender )
    Assert.notNull( sender, "User must be specified" );

    String sql = "delete from messageconversation_messages where messageid in (" +
        "select messageid from message where userid = " + sender.getId() + ")";

    getSqlQuery( sql ).executeUpdate();

    String hql = "delete Message m where m.sender = :sender";

    return getQuery( hql )
        .setParameter( "sender", sender )
Example #7
Source File:    From localization_nifi with Apache License 2.0 6 votes vote down vote up
 * Fills the internal message queue if such queue is empty. This is due to
 * the fact that per single session there may be multiple messages retrieved
 * from the email server (see FETCH_SIZE).
private synchronized void fillMessageQueueIfNecessary() {
    if (this.messageQueue.isEmpty()) {
        Object[] messages;
        try {
            messages = this.messageReceiver.receive();
        } catch (MessagingException e) {
            String errorMsg = "Failed to receive messages from Email server: [" + e.getClass().getName()
                    + " - " + e.getMessage();
            throw new ProcessException(errorMsg, e);

        if (messages != null) {
            for (Object message : messages) {
                Assert.isTrue(message instanceof Message, "Message is not an instance of javax.mail.Message");
                this.messageQueue.offer((Message) message);
Example #8
Source File:    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
 * Add a cookie with the given value to the response,
 * using the cookie descriptor settings of this generator.
 * <p>Delegates to {@link #createCookie} for cookie creation.
 * @param response the HTTP response to add the cookie to
 * @param cookieValue the value of the cookie to add
 * @see #setCookieName
 * @see #setCookieDomain
 * @see #setCookiePath
 * @see #setCookieMaxAge
public void addCookie(HttpServletResponse response, String cookieValue) {
	Assert.notNull(response, "HttpServletResponse must not be null");
	Cookie cookie = createCookie(cookieValue);
	Integer maxAge = getCookieMaxAge();
	if (maxAge != null) {
	if (isCookieSecure()) {
	if (isCookieHttpOnly()) {
	if (logger.isDebugEnabled()) {
		logger.debug("Added cookie with name [" + getCookieName() + "] and value [" + cookieValue + "]");
Example #9
Source File:    From spring-boot-rsocket with Apache License 2.0 6 votes vote down vote up
private HttpServer createHttpServer() {
	HttpServer server = HttpServer.create();
	if (this.resourceFactory != null) {
		LoopResources resources = this.resourceFactory.getLoopResources();
				"No LoopResources: is ReactorResourceFactory not initialized yet?");
		server = server.tcpConfiguration((tcpServer) -> tcpServer.runOn(resources)
	else {
		server = server.tcpConfiguration(
				(tcpServer) -> tcpServer.addressSupplier(this::getListenAddress));
	if (getSsl() != null && getSsl().isEnabled()) {
		SslServerCustomizer sslServerCustomizer = new SslServerCustomizer(getSsl(),
				getHttp2(), getSslStoreProvider());
		server = sslServerCustomizer.apply(server);
	if (getCompression() != null && getCompression().getEnabled()) {
		CompressionCustomizer compressionCustomizer = new CompressionCustomizer(
		server = compressionCustomizer.apply(server);
	server = server.protocol(listProtocols()).forwarded(this.useForwardHeaders);
	return applyCustomizers(server);
Example #10
Source File:    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public <T> T browseSelected(final String queueName, final String messageSelector, final BrowserCallback<T> action)
		throws JmsException {

	Assert.notNull(action, "Callback object must not be null");
	return execute(new SessionCallback<T>() {
		public T doInJms(Session session) throws JMSException {
			Queue queue = (Queue) getDestinationResolver().resolveDestinationName(session, queueName, false);
			QueueBrowser browser = createBrowser(session, queue, messageSelector);
			try {
				return action.doInJms(session, browser);
			finally {
	}, true);
Example #11
Source File:    From spring-cloud-stream-binder-rabbit with Apache License 2.0 6 votes vote down vote up
public void onInit() throws Exception {
	if (this.clustered) {
		String[] addresses = StringUtils.commaDelimitedListToStringArray(

				addresses.length == this.adminAddresses.length
						&& addresses.length == this.nodes.length,
				"'addresses', 'adminAddresses', and 'nodes' properties must have equal length");

		this.connectionFactory = new LocalizedQueueConnectionFactory(
				this.connectionFactory, addresses, this.adminAddresses, this.nodes,
		this.destroyConnectionFactory = true;
Example #12
Source File:    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
 * Determine the ultimate target class of the given bean instance, traversing
 * not only a top-level proxy but any number of nested proxies as well &mdash;
 * as long as possible without side effects, that is, just for singleton targets.
 * @param candidate the instance to check (might be an AOP proxy)
 * @return the ultimate target class (or the plain class of the given
 * object as fallback; never {@code null})
 * @see org.springframework.aop.TargetClassAware#getTargetClass()
 * @see Advised#getTargetSource()
public static Class<?> ultimateTargetClass(Object candidate) {
	Assert.notNull(candidate, "Candidate object must not be null");
	Object current = candidate;
	Class<?> result = null;
	while (current instanceof TargetClassAware) {
		result = ((TargetClassAware) current).getTargetClass();
		Object nested = null;
		if (current instanceof Advised) {
			TargetSource targetSource = ((Advised) current).getTargetSource();
			if (targetSource instanceof SingletonTargetSource) {
				nested = ((SingletonTargetSource) targetSource).getTarget();
		current = nested;
	if (result == null) {
		result = (AopUtils.isCglibProxy(candidate) ? candidate.getClass().getSuperclass() : candidate.getClass());
	return result;
Example #13
Source File:    From lams with GNU General Public License v2.0 6 votes vote down vote up
 * Apply the specified timeout - overridden by the current transaction timeout,
 * if any - to the given JDBC Statement object.
 * @param stmt the JDBC Statement object
 * @param dataSource the DataSource that the Connection was obtained from
 * @param timeout the timeout to apply (or 0 for no timeout outside of a transaction)
 * @throws SQLException if thrown by JDBC methods
 * @see java.sql.Statement#setQueryTimeout
public static void applyTimeout(Statement stmt, DataSource dataSource, int timeout) throws SQLException {
	Assert.notNull(stmt, "No Statement specified");
	ConnectionHolder holder = null;
	if (dataSource != null) {
		holder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
	if (holder != null && holder.hasTimeout()) {
		// Remaining transaction timeout overrides specified value.
	else if (timeout >= 0) {
		// No current transaction timeout -> apply specified value.
Example #14
Source File:    From spring-analysis-note with MIT License 6 votes vote down vote up
public Object getAttribute(String name, int scope) {
	Assert.notNull(name, "Attribute name must not be null");
	switch (scope) {
		case PAGE_SCOPE:
			return getAttribute(name);
			return this.request.getAttribute(name);
			HttpSession session = this.request.getSession(false);
			return (session != null ? session.getAttribute(name) : null);
			return this.servletContext.getAttribute(name);
			throw new IllegalArgumentException("Invalid scope: " + scope);
Example #15
Source File:    From spring-analysis-note with MIT License 5 votes vote down vote up
 * Add a resource transformer to the chain.
 * @param transformer the transformer to add
 * @return the current instance for chained method invocation
public ResourceChainRegistration addTransformer(ResourceTransformer transformer) {
	Assert.notNull(transformer, "The provided ResourceTransformer should not be null");
	if (transformer instanceof CssLinkResourceTransformer) {
		this.hasCssLinkTransformer = true;
	return this;
Example #16
Source File:    From spring-analysis-note with MIT License 5 votes vote down vote up
 * Find a HeaderValueHolder by name, ignoring casing.
 * @param headers the Map of header names to HeaderValueHolders
 * @param name the name of the desired header
 * @return the corresponding HeaderValueHolder, or {@code null} if none found
public static HeaderValueHolder getByName(Map<String, HeaderValueHolder> headers, String name) {
	Assert.notNull(name, "Header name must not be null");
	for (String headerName : headers.keySet()) {
		if (headerName.equalsIgnoreCase(name)) {
			return headers.get(headerName);
	return null;
Example #17
Source File:    From halo with GNU General Public License v3.0 5 votes vote down vote up
public Page<Post> pagePostsBy(Integer tagId, Pageable pageable) {
    Assert.notNull(tagId, "Tag id must not be null");
    Assert.notNull(pageable, "Page info must not be null");

    // Find all post ids
    Set<Integer> postIds = postTagRepository.findAllPostIdsByTagId(tagId);

    return postRepository.findAllByIdIn(postIds, pageable);
Example #18
Source File:    From spring-analysis-note with MIT License 5 votes vote down vote up
 * Note that as of 5.0.3, the creation of the response, which may block
 * intentionally, is separated from request count tracking, and this
 * method no longer increments the count transparently. Instead
 * {@link #incrementAndValidate()} must be invoked independently.
public ClientHttpResponse createResponse(@Nullable ClientHttpRequest request) throws IOException {
	ResponseCreator responseCreator = getResponseCreator();
	Assert.state(responseCreator != null, "createResponse() called before ResponseCreator was set");
	return responseCreator.createResponse(request);
Example #19
Source File:    From spring-vault with Apache License 2.0 5 votes vote down vote up
 * Create a {@link Policy} from one or more {@code rules}.
 * @param rules must not be {@literal null}.
 * @return the {@link Policy} object containing {@code rules}.
public static Policy of(Rule... rules) {

	Assert.notNull(rules, "Rules must not be null");
	Assert.noNullElements(rules, "Rules must not contain null elements");

	return new Policy(new LinkedHashSet<>(Arrays.asList(rules)));
Example #20
Source File:    From full-teaching with Apache License 2.0 5 votes vote down vote up
public void setAndGetCourseDetailsForumTest() {
	CourseDetails cd = new CourseDetails();
	Forum forum = new Forum();
Example #21
Source File:    From java-technology-stack with MIT License 5 votes vote down vote up
 * Create a new {@code UrlResource} based on the given URL object.
 * @param url a URL
public UrlResource(URL url) {
	Assert.notNull(url, "URL must not be null");
	this.url = url;
	this.cleanedUrl = getCleanedUrl(this.url, url.toString());
	this.uri = null;
Example #22
Source File:    From spring-analysis-note with MIT License 5 votes vote down vote up
 * Convert the given {@linkplain RouterFunction router function} into a {@link WebHandler},
 * using the given strategies.
 * @param routerFunction the router function to convert
 * @param strategies the strategies to use
 * @return a web handler that handles web request using the given router function
public static WebHandler toWebHandler(RouterFunction<?> routerFunction, HandlerStrategies strategies) {
	Assert.notNull(routerFunction, "RouterFunction must not be null");
	Assert.notNull(strategies, "HandlerStrategies must not be null");

	return exchange -> {
		ServerRequest request = new DefaultServerRequest(exchange, strategies.messageReaders());
		addAttributes(exchange, request);
		return routerFunction.route(request)
				.flatMap(handlerFunction -> wrapException(() -> handlerFunction.handle(request)))
				.flatMap(response -> wrapException(() -> response.writeTo(exchange,
						new HandlerStrategiesResponseContext(strategies))));
Example #23
Source File:    From flowable-engine with Apache License 2.0 5 votes vote down vote up
 * Register a new {@link JmsListenerEndpoint} alongside the
 * {@link JmsListenerContainerFactory} to use to create the underlying container.
 * <p>The {@code factory} may be {@code null} if the default factory has to be
 * used for that endpoint.
protected void registerEndpoint(JmsListenerEndpoint endpoint, JmsListenerContainerFactory<?> factory) {
    Assert.notNull(endpoint, "Endpoint must not be null");
    Assert.hasText(endpoint.getId(), "Endpoint id must be set");

    Assert.state(this.endpointRegistry != null, "No JmsListenerEndpointRegistry set");
    endpointRegistry.registerListenerContainer(endpoint, resolveContainerFactory(endpoint, factory), true);
Example #24
Source File:    From halo with GNU General Public License v3.0 5 votes vote down vote up
public ThemeProperty resolve(@NonNull String content) throws IOException {
    Assert.hasText(content, "Theme file content must not be null");

    return YamlResolver.INSTANCE.getYamlMapper().readValue(content, ThemeProperty.class);
Example #25
Source File:    From java-technology-stack with MIT License 5 votes vote down vote up
 * Process the given {@link JmsListener} annotation on the given method,
 * registering a corresponding endpoint for the given bean instance.
 * @param jmsListener the annotation to process
 * @param mostSpecificMethod the annotated method
 * @param bean the instance to invoke the method on
 * @see #createMethodJmsListenerEndpoint()
 * @see JmsListenerEndpointRegistrar#registerEndpoint
protected void processJmsListener(JmsListener jmsListener, Method mostSpecificMethod, Object bean) {
	Method invocableMethod = AopUtils.selectInvocableMethod(mostSpecificMethod, bean.getClass());

	MethodJmsListenerEndpoint endpoint = createMethodJmsListenerEndpoint();
	if (StringUtils.hasText(jmsListener.selector())) {
	if (StringUtils.hasText(jmsListener.subscription())) {
	if (StringUtils.hasText(jmsListener.concurrency())) {

	JmsListenerContainerFactory<?> factory = null;
	String containerFactoryBeanName = resolve(jmsListener.containerFactory());
	if (StringUtils.hasText(containerFactoryBeanName)) {
		Assert.state(this.beanFactory != null, "BeanFactory must be set to obtain container factory by bean name");
		try {
			factory = this.beanFactory.getBean(containerFactoryBeanName, JmsListenerContainerFactory.class);
		catch (NoSuchBeanDefinitionException ex) {
			throw new BeanInitializationException("Could not register JMS listener endpoint on [" +
					mostSpecificMethod + "], no " + JmsListenerContainerFactory.class.getSimpleName() +
					" with id '" + containerFactoryBeanName + "' was found in the application context", ex);

	this.registrar.registerEndpoint(endpoint, factory);
Example #26
Source File:    From seata-samples with Apache License 2.0 5 votes vote down vote up
private static void transactionCommitDemo() throws InterruptedException {
    String txId = tccTransactionService.doTransactionCommit();
    Assert.isTrue(StringUtils.isNotBlank(txId), "事务开启失败");

    System.out.println("transaction commit demo finish.");
Example #27
Source File:    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	try {
		Connection conToUse = con;
		if (this.nativeJdbcExtractor != null &&
				this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativeStatements()) {
			conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
		stmt = conToUse.createStatement();
		Statement stmtToUse = stmt;
		if (this.nativeJdbcExtractor != null) {
			stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt);
		T result = action.doInStatement(stmtToUse);
		return result;
	catch (SQLException ex) {
		// Release Connection early, to avoid potential connection pool deadlock
		// in the case when the exception translator hasn't been initialized yet.
		stmt = null;
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
	finally {
		DataSourceUtils.releaseConnection(con, getDataSource());
Example #28
Source File:    From spring-analysis-note with MIT License 5 votes vote down vote up
private MockHttpServletResponse unwrapResponseIfNecessary(ServletResponse servletResponse) {
	while (servletResponse instanceof HttpServletResponseWrapper) {
		servletResponse = ((HttpServletResponseWrapper) servletResponse).getResponse();
	Assert.isInstanceOf(MockHttpServletResponse.class, servletResponse);
	return (MockHttpServletResponse) servletResponse;
Example #29
Source File:    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
private ClientAuthentication appIdAuthentication(VaultProperties vaultProperties) {

		VaultProperties.AppIdProperties appId = vaultProperties.getAppId();
				"UserId ( must not be empty");

		AppIdAuthenticationOptions authenticationOptions = AppIdAuthenticationOptions
				.builder().appId(vaultProperties.getApplicationName()) //
				.path(appId.getAppIdPath()) //

		return new AppIdAuthentication(authenticationOptions, this.restOperations);
Example #30
Source File:    From oauth-server with Apache License 2.0 5 votes vote down vote up
private String obtainMatchingRedirect(Set<String> redirectUris, String requestedRedirect) {
    Assert.notEmpty(redirectUris, "Redirect URIs cannot be empty");

    if (redirectUris.size() == 1 && requestedRedirect == null) {
        return redirectUris.iterator().next();
    for (String redirectUri : redirectUris) {
        if (requestedRedirect != null && redirectMatches(requestedRedirect, redirectUri)) {
            return requestedRedirect;
    throw new RedirectMismatchException("Invalid redirect: " + requestedRedirect
            + " does not match one of the registered values: " + redirectUris.toString());