Java Code Examples for org.springframework.util.Assert

The following examples show how to use org.springframework.util.Assert. These examples are extracted from open source projects. 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 Project: java-technology-stack   Author: codeEngraver   File: AbstractSingleCheckedElementTag.java    License: 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}.
 */
@Override
protected int writeTagContent(TagWriter tagWriter) throws JspException {
	tagWriter.startTag("input");
	String id = resolveId();
	writeOptionalAttribute(tagWriter, "id", id);
	writeOptionalAttribute(tagWriter, "name", getName());
	writeOptionalAttributes(tagWriter);
	writeTagDetails(tagWriter);
	tagWriter.endTag();

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

	return SKIP_BODY;
}
 
Example #2
Source Project: foremast   Author: intuit   File: HandlerMappingIntrospector.java    License: 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) {
            continue;
        }
        if (handler instanceof HandlerExecutionChain) {
            return (HandlerExecutionChain)handler;
        }
        throw new IllegalStateException("HandlerMapping is not a MatchableHandlerMapping");
    }
    return null;
}
 
Example #3
Source Project: onetwo   Author: wayshall   File: FormHttpMessageConverter.java    License: 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);
	outputMessage.getHeaders().setContentType(contentType);

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

	final byte[] bytes = serializeForm(formData, charset).getBytes(charset);
	outputMessage.getHeaders().setContentLength(bytes.length);

	if (outputMessage instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
		streamingOutputMessage.setBody(outputStream -> StreamUtils.copy(bytes, outputStream));
	}
	else {
		StreamUtils.copy(bytes, outputMessage.getBody());
	}
}
 
Example #4
Source Project: java-platform   Author: xiangxik   File: QQOauthPlugin.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getAccessToken(String code) {
	Assert.hasText(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("https://graph.qq.com/oauth2.0/token", 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 Project: xechat   Author: anlingyi   File: ChatRecordAspect.java    License: MIT License 6 votes vote down vote up
@Before("chatRecordPointcut()")
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;
            break;
        }
    }

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

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

    log.debug("添加聊天记录 -> {}", messageVO);
    chatRecordService.addRecord(ChatRecordDTO.toChatRecordDTO(messageVO));
}
 
Example #6
@Override
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 )
        .executeUpdate();
}
 
Example #7
Source Project: localization_nifi   Author: wangrenlei   File: AbstractEmailProcessor.java    License: 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();
            this.getLogger().error(errorMsg);
            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 Project: spring4-understanding   Author: langtianya   File: CookieGenerator.java    License: 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) {
		cookie.setMaxAge(maxAge);
	}
	if (isCookieSecure()) {
		cookie.setSecure(true);
	}
	if (isCookieHttpOnly()) {
		cookie.setHttpOnly(true);
	}
	response.addCookie(cookie);
	if (logger.isDebugEnabled()) {
		logger.debug("Added cookie with name [" + getCookieName() + "] and value [" + cookieValue + "]");
	}
}
 
Example #9
Source Project: spring-boot-rsocket   Author: CollaborationInEncapsulation   File: RSocketNettyReactiveWebServerFactory.java    License: 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();
		Assert.notNull(resources,
				"No LoopResources: is ReactorResourceFactory not initialized yet?");
		server = server.tcpConfiguration((tcpServer) -> tcpServer.runOn(resources)
				.addressSupplier(this::getListenAddress));
	}
	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(
				getCompression());
		server = compressionCustomizer.apply(server);
	}
	server = server.protocol(listProtocols()).forwarded(this.useForwardHeaders);
	return applyCustomizers(server);
}
 
Example #10
Source Project: spring4-understanding   Author: langtianya   File: JmsTemplate.java    License: Apache License 2.0 6 votes vote down vote up
@Override
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>() {
		@Override
		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 {
				JmsUtils.closeQueueBrowser(browser);
			}
		}
	}, true);
}
 
Example #11
Source Project: spring-cloud-stream-binder-rabbit   Author: spring-cloud   File: RabbitMessageChannelBinder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onInit() throws Exception {
	super.onInit();
	if (this.clustered) {
		String[] addresses = StringUtils.commaDelimitedListToStringArray(
				this.rabbitProperties.getAddresses());

		Assert.state(
				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.rabbitProperties.getVirtualHost(),
				this.rabbitProperties.getUsername(),
				this.rabbitProperties.getPassword(),
				this.rabbitProperties.getSsl().getEnabled(),
				this.rabbitProperties.getSsl().getKeyStore(),
				this.rabbitProperties.getSsl().getTrustStore(),
				this.rabbitProperties.getSsl().getKeyStorePassword(),
				this.rabbitProperties.getSsl().getTrustStorePassword());
		this.destroyConnectionFactory = true;
	}
}
 
Example #12
Source Project: spring4-understanding   Author: langtianya   File: AopProxyUtils.java    License: 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 Project: lams   Author: lamsfoundation   File: DataSourceUtils.java    License: 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.
		stmt.setQueryTimeout(holder.getTimeToLiveInSeconds());
	}
	else if (timeout >= 0) {
		// No current transaction timeout -> apply specified value.
		stmt.setQueryTimeout(timeout);
	}
}
 
Example #14
Source Project: spring-analysis-note   Author: Vip-Augus   File: MockPageContext.java    License: MIT License 6 votes vote down vote up
@Override
@Nullable
public Object getAttribute(String name, int scope) {
	Assert.notNull(name, "Attribute name must not be null");
	switch (scope) {
		case PAGE_SCOPE:
			return getAttribute(name);
		case REQUEST_SCOPE:
			return this.request.getAttribute(name);
		case SESSION_SCOPE:
			HttpSession session = this.request.getSession(false);
			return (session != null ? session.getAttribute(name) : null);
		case APPLICATION_SCOPE:
			return this.servletContext.getAttribute(name);
		default:
			throw new IllegalArgumentException("Invalid scope: " + scope);
	}
}
 
Example #15
Source Project: spring-analysis-note   Author: Vip-Augus   File: ResourceChainRegistration.java    License: 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");
	this.transformers.add(transformer);
	if (transformer instanceof CssLinkResourceTransformer) {
		this.hasCssLinkTransformer = true;
	}
	return this;
}
 
Example #16
Source Project: spring-analysis-note   Author: Vip-Augus   File: HeaderValueHolder.java    License: 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
 */
@Nullable
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 Project: halo   Author: halo-dev   File: PostTagServiceImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
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 Project: spring-analysis-note   Author: Vip-Augus   File: DefaultRequestExpectation.java    License: 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.
 */
@Override
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 Project: spring-vault   Author: spring-projects   File: Policy.java    License: 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 Project: full-teaching   Author: pabloFuente   File: CourseDetailsUnitaryTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void setAndGetCourseDetailsForumTest() {
	CourseDetails cd = new CourseDetails();
	Forum forum = new Forum();
	cd.setForum(forum);
	Assert.notNull(cd);
	Assert.isTrue(forum.equals(cd.getForum()));
}
 
Example #21
Source Project: java-technology-stack   Author: codeEngraver   File: UrlResource.java    License: 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 Project: spring-analysis-note   Author: Vip-Augus   File: RouterFunctions.java    License: 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)
				.defaultIfEmpty(notFound())
				.flatMap(handlerFunction -> wrapException(() -> handlerFunction.handle(request)))
				.flatMap(response -> wrapException(() -> response.writeTo(exchange,
						new HandlerStrategiesResponseContext(strategies))));
	};
}
 
Example #23
Source Project: flowable-engine   Author: flowable   File: JmsChannelModelProcessor.java    License: 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 Project: halo   Author: halo-dev   File: YamlThemePropertyResolver.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
@NonNull
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 Project: java-technology-stack   Author: codeEngraver   File: JmsListenerAnnotationBeanPostProcessor.java    License: 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();
	endpoint.setBean(bean);
	endpoint.setMethod(invocableMethod);
	endpoint.setMostSpecificMethod(mostSpecificMethod);
	endpoint.setMessageHandlerMethodFactory(this.messageHandlerMethodFactory);
	endpoint.setEmbeddedValueResolver(this.embeddedValueResolver);
	endpoint.setBeanFactory(this.beanFactory);
	endpoint.setId(getEndpointId(jmsListener));
	endpoint.setDestination(resolve(jmsListener.destination()));
	if (StringUtils.hasText(jmsListener.selector())) {
		endpoint.setSelector(resolve(jmsListener.selector()));
	}
	if (StringUtils.hasText(jmsListener.subscription())) {
		endpoint.setSubscription(resolve(jmsListener.subscription()));
	}
	if (StringUtils.hasText(jmsListener.concurrency())) {
		endpoint.setConcurrency(resolve(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 Project: seata-samples   Author: seata   File: DubboTccTransactionStarter.java    License: Apache License 2.0 5 votes vote down vote up
private static void transactionCommitDemo() throws InterruptedException {
    String txId = tccTransactionService.doTransactionCommit();
    System.out.println(txId);
    Assert.isTrue(StringUtils.isNotBlank(txId), "事务开启失败");

    System.out.println("transaction commit demo finish.");
}
 
Example #27
Source Project: spring4-understanding   Author: langtianya   File: JdbcTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
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();
		applyStatementSettings(stmt);
		Statement stmtToUse = stmt;
		if (this.nativeJdbcExtractor != null) {
			stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt);
		}
		T result = action.doInStatement(stmtToUse);
		handleWarnings(stmt);
		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.
		JdbcUtils.closeStatement(stmt);
		stmt = null;
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
	}
	finally {
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example #28
Source Project: spring-analysis-note   Author: Vip-Augus   File: MockMvc.java    License: 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 Project: spring-cloud-vault   Author: spring-cloud   File: ClientAuthenticationFactory.java    License: Apache License 2.0 5 votes vote down vote up
private ClientAuthentication appIdAuthentication(VaultProperties vaultProperties) {

		VaultProperties.AppIdProperties appId = vaultProperties.getAppId();
		Assert.hasText(appId.getUserId(),
				"UserId (spring.cloud.vault.app-id.user-id) must not be empty");

		AppIdAuthenticationOptions authenticationOptions = AppIdAuthenticationOptions
				.builder().appId(vaultProperties.getApplicationName()) //
				.path(appId.getAppIdPath()) //
				.userIdMechanism(getAppIdMechanism(appId)).build();

		return new AppIdAuthentication(authenticationOptions, this.restOperations);
	}
 
Example #30
Source Project: oauth-server   Author: choerodon   File: ChoerodonRedirectResolver.java    License: 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());
}