下面列出了怎么用org.springframework.util.Assert的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
/**
* 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;
}
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());
}
}
@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");
}
@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));
}
@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();
}
/**
* 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);
}
}
}
}
/**
* 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 + "]");
}
}
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);
}
@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);
}
@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;
}
}
/**
* 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 —
* 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;
}
/**
* 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);
}
}
@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);
}
}
/**
* 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;
}
/**
* 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;
}
@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);
}
/**
* 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);
}
/**
* 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)));
}
@Test
public void setAndGetCourseDetailsForumTest() {
CourseDetails cd = new CourseDetails();
Forum forum = new Forum();
cd.setForum(forum);
Assert.notNull(cd);
Assert.isTrue(forum.equals(cd.getForum()));
}
/**
* 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;
}
/**
* 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))));
};
}
/**
* 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);
}
@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);
}
/**
* 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);
}
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.");
}
@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());
}
}
private MockHttpServletResponse unwrapResponseIfNecessary(ServletResponse servletResponse) {
while (servletResponse instanceof HttpServletResponseWrapper) {
servletResponse = ((HttpServletResponseWrapper) servletResponse).getResponse();
}
Assert.isInstanceOf(MockHttpServletResponse.class, servletResponse);
return (MockHttpServletResponse) servletResponse;
}
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);
}
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());
}