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: HibernateMessageConversationStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #2
Source File: RSocketNettyReactiveWebServerFactory.java    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();
		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 #3
Source File: CookieGenerator.java    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) {
		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 #4
Source File: AbstractEmailProcessor.java    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();
            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 #5
Source File: JmsTemplate.java    From spring4-understanding with 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 #6
Source File: RabbitMessageChannelBinder.java    From spring-cloud-stream-binder-rabbit with 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 #7
Source File: AopProxyUtils.java    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 #8
Source File: QQOauthPlugin.java    From java-platform with 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 #9
Source File: FormHttpMessageConverter.java    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);
	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 #10
Source File: DataSourceUtils.java    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.
		stmt.setQueryTimeout(holder.getTimeToLiveInSeconds());
	}
	else if (timeout >= 0) {
		// No current transaction timeout -> apply specified value.
		stmt.setQueryTimeout(timeout);
	}
}
 
Example #11
Source File: HandlerMappingIntrospector.java    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) {
            continue;
        }
        if (handler instanceof HandlerExecutionChain) {
            return (HandlerExecutionChain)handler;
        }
        throw new IllegalStateException("HandlerMapping is not a MatchableHandlerMapping");
    }
    return null;
}
 
Example #12
Source File: AbstractSingleCheckedElementTag.java    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}.
 */
@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 #13
Source File: ChatRecordAspect.java    From xechat with 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 #14
Source File: MockPageContext.java    From spring-analysis-note with 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 File: PostServiceImpl.java    From spring-boot-data-aggregator with Apache License 2.0 5 votes vote down vote up
@DataProvider("posts")
@Override
public List<Post> getPosts(@InvokeParameter("userId") Long userId) {
    Assert.isTrue(userId != null && userId != 0, "userId must be not null and gt 0!");
    try {
        Thread.sleep(1000L);
    } catch (InterruptedException e) {
        //
    }
    Post post = new Post();
    post.setTitle("spring data aggregate example");
    post.setContent("No active profile set, falling back to default profiles");
    return Collections.singletonList(post);
}
 
Example #16
Source File: MockMvc.java    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 #17
Source File: ChoerodonRedirectResolver.java    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());
}
 
Example #18
Source File: ClientAuthenticationFactory.java    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();
		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 #19
Source File: SchedulerIntegrationTest.java    From spring-cloud-deployer with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() throws InterruptedException {
	String parameterThatMayNeedEscaping = properties.getParameterThatMayNeedEscaping();
	if (parameterThatMayNeedEscaping != null && !SchedulerIntegrationTestProperties.FUNNY_CHARACTERS.equals(parameterThatMayNeedEscaping)) {
		throw new IllegalArgumentException(String.format("Expected 'parameterThatMayNeedEscaping' value to be equal to '%s', but was '%s'", SchedulerIntegrationTestProperties.FUNNY_CHARACTERS, parameterThatMayNeedEscaping));
	}

	String commandLineArgValueThatMayNeedEscaping = properties.getCommandLineArgValueThatMayNeedEscaping();
	if (commandLineArgValueThatMayNeedEscaping != null && !SchedulerIntegrationTestProperties.FUNNY_CHARACTERS.equals(commandLineArgValueThatMayNeedEscaping)) {
		throw new IllegalArgumentException(String.format("Expected 'commandLineArgValueThatMayNeedEscaping' value to be equal to '%s', but was '%s'", SchedulerIntegrationTestProperties.FUNNY_CHARACTERS, commandLineArgValueThatMayNeedEscaping));
	}

	Assert.notNull(properties.getInstanceIndex(), "instanceIndex should have been set by deployer or runtime");

	if (properties.getMatchInstances().isEmpty() || properties.getMatchInstances().contains(properties.getInstanceIndex())) {
		log.info("Waiting for %dms before allowing further initialization and actuator startup...", properties.getInitDelay());
		Thread.sleep(properties.getInitDelay());
		log.info("... done");
		if (properties.getKillDelay() >= 0) {
			log.info("Will kill this process in %dms%n", properties.getKillDelay());
			new Thread() {

				@Override
				public void run() {
					try {
						Thread.sleep(properties.getKillDelay());
						System.exit(properties.getExitCode());
					}
					catch (InterruptedException e) {
						throw new RuntimeException(e);
					}
				}
			}.start();
		}
	}
}
 
Example #20
Source File: ResourceChainRegistration.java    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");
	this.transformers.add(transformer);
	if (transformer instanceof CssLinkResourceTransformer) {
		this.hasCssLinkTransformer = true;
	}
	return this;
}
 
Example #21
Source File: MergedContextConfiguration.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Get the parent {@link ApplicationContext} for the context defined by this
 * {@code MergedContextConfiguration} from the context cache.
 * <p>If the parent context has not yet been loaded, it will be loaded, stored
 * in the cache, and then returned.
 * @return the parent {@code ApplicationContext} or {@code null} if there is no parent
 * @see #getParent()
 * @since 3.2.2
 */
@Nullable
public ApplicationContext getParentApplicationContext() {
	if (this.parent == null) {
		return null;
	}
	Assert.state(this.cacheAwareContextLoaderDelegate != null,
			"Cannot retrieve a parent application context without access to the CacheAwareContextLoaderDelegate");
	return this.cacheAwareContextLoaderDelegate.loadContext(this.parent);
}
 
Example #22
Source File: UKTools.java    From youkefu with Apache License 2.0 5 votes vote down vote up
public static void copyProperties(Object source, Object target,String... ignoreProperties)  
        throws BeansException {  
  
    Assert.notNull(source, "Source must not be null");  
    Assert.notNull(target, "Target must not be null");  
  
    Class<?> actualEditable = target.getClass();  
    PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(actualEditable);  
    List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;  
  
    for (PropertyDescriptor targetPd : targetPds) {  
        Method writeMethod = targetPd.getWriteMethod();  
        if (writeMethod != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {  
            PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(), targetPd.getName());  
            if (sourcePd != null && !targetPd.getName().equalsIgnoreCase("id")) {  
                Method readMethod = sourcePd.getReadMethod();  
                if (readMethod != null &&  
                        ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {  
                    try {  
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {  
                            readMethod.setAccessible(true);  
                        }  
                        Object value = readMethod.invoke(source);  
                        if(value != null){  //只拷贝不为null的属性 by zhao  
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {  
                                writeMethod.setAccessible(true);  
                            }  
                            writeMethod.invoke(target, value);  
                        }  
                    }  
                    catch (Throwable ex) {  
                        throw new FatalBeanException(  
                                "Could not copy property '" + targetPd.getName() + "' from source to target", ex);  
                    }  
                }  
            }  
        }  
    }  
}
 
Example #23
Source File: DefaultJpaRepository.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public int executeUpdateBySql(String sql, NamedParams params) {
    Assert.notNull(params, "Query params must not be null!");
    Assert.hasText(sql, "Sql must has text!");

    Query query = em.createNativeQuery(sql);
    setQueryParams(query, params);
   return query.executeUpdate();
}
 
Example #24
Source File: ReflectionUtils.java    From ace-cache with Apache License 2.0 5 votes vote down vote up
public static Class<?> getUserClass(Object instance) {
    Assert.notNull(instance, "Instance must not be null");
    Class clazz = instance.getClass();
    if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
        Class<?> superClass = clazz.getSuperclass();
        if (superClass != null && !Object.class.equals(superClass)) {
            return superClass;
        }
    }
    return clazz;

}
 
Example #25
Source File: ReactiveAggregateQueryProviderTest.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "queryMethods", expectedExceptions = {JsonParseException.class})
public void testCreateAggregateQuery(String methodName) throws Exception {
  ReactiveAggregateQuerySupportingRepositoryFactory factory = new ReactiveAggregateQuerySupportingRepositoryFactory(mongoOperations,
                                                                                                                    queryExecutor);
  Optional<QueryLookupStrategy> lookupStrategy = factory.getQueryLookupStrategy(CREATE_IF_NOT_FOUND, evaluationContextProvider);

  Assert.isTrue(lookupStrategy.isPresent(), "Lookup strategy must not be null");
  Method method = ReactiveTestAggregateRepository22.class.getMethod(methodName);
  RepositoryMetadata repositoryMetadata = new DefaultRepositoryMetadata(ReactiveTestAggregateRepository22.class);
  ProjectionFactory projectionFactory = new SpelAwareProxyProjectionFactory();
  RepositoryQuery query = lookupStrategy.get().resolveQuery(method, repositoryMetadata, projectionFactory, null);
  assertNotNull(query);
  Object object = query.execute(new Object[0]);
  assertNull(object);
}
 
Example #26
Source File: JdbcTemplate.java    From spring4-understanding with 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 #27
Source File: DubboTccTransactionStarter.java    From seata-samples with 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 #28
Source File: JmsListenerAnnotationBeanPostProcessor.java    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();
	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 #29
Source File: YamlThemePropertyResolver.java    From halo with 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 #30
Source File: JmsChannelModelProcessor.java    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);
}