Java Code Examples for org.springframework.util.Assert#state()

The following examples show how to use org.springframework.util.Assert#state() . 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: StompBrokerRelayMessageHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void handleMessage(Message<byte[]> message) {
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	Assert.state(accessor != null, "No StompHeaderAccessor");
	accessor.setSessionId(this.sessionId);
	Principal user = this.connectHeaders.getUser();
	if (user != null) {
		accessor.setUser(user);
	}

	StompCommand command = accessor.getCommand();
	if (StompCommand.CONNECTED.equals(command)) {
		if (logger.isDebugEnabled()) {
			logger.debug("Received " + accessor.getShortLogMessage(EMPTY_PAYLOAD));
		}
		afterStompConnected(accessor);
	}
	else if (logger.isErrorEnabled() && StompCommand.ERROR.equals(command)) {
		logger.error("Received " + accessor.getShortLogMessage(message.getPayload()));
	}
	else if (logger.isTraceEnabled()) {
		logger.trace("Received " + accessor.getDetailedLogMessage(message.getPayload()));
	}

	handleInboundMessage(message);
}
 
Example 2
Source File: AzureMsiAuthentication.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
private VaultToken createTokenUsingAzureMsiCompute() {

		Map<String, String> login = getAzureLogin(this.options.getRole(), getVmEnvironment(), getAccessToken());

		try {

			VaultResponse response = this.vaultRestOperations
					.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);

			Assert.state(response != null && response.getAuth() != null, "Auth field must not be null");

			if (logger.isDebugEnabled()) {
				logger.debug("Login successful using Azure authentication");
			}

			return LoginTokenUtil.from(response.getAuth());
		}
		catch (RestClientException e) {
			throw VaultLoginException.create("Azure", e);
		}
	}
 
Example 3
Source File: WriteResultPublisher.java    From spring-analysis-note with MIT License 5 votes vote down vote up
void publishError(WriteResultPublisher publisher, Throwable t) {
	if (publisher.changeState(this, COMPLETED)) {
		Subscriber<? super Void> s = publisher.subscriber;
		Assert.state(s != null, "No subscriber");
		s.onError(t);
	}
	else {
		publisher.state.get().publishError(publisher, t);
	}
}
 
Example 4
Source File: ServerEndpointExporter.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void registerEndpoint(ServerEndpointConfig endpointConfig) {
	ServerContainer serverContainer = getServerContainer();
	Assert.state(serverContainer != null, "No ServerContainer set");
	try {
		if (logger.isDebugEnabled()) {
			logger.debug("Registering ServerEndpointConfig: " + endpointConfig);
		}
		serverContainer.addEndpoint(endpointConfig);
	}
	catch (DeploymentException ex) {
		throw new IllegalStateException("Failed to register ServerEndpointConfig: " + endpointConfig, ex);
	}
}
 
Example 5
Source File: DoNotExecuteMongeezPostProcessor.java    From mongeez-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String[] mongeezBeanNames = beanFactory.getBeanNamesForType(Mongeez.class);
    Assert.state(mongeezBeanNames.length == 1);
    BeanDefinition beanDefinition = beanFactory.getBeanDefinition(mongeezBeanNames[0]);
    Assert.state(beanDefinition instanceof RootBeanDefinition);
    ((RootBeanDefinition) beanDefinition).setInitMethodName(null);
}
 
Example 6
Source File: ModelFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Invoke model attribute methods to populate the model.
 * Attributes are added only if not already present in the model.
 */
private void invokeModelAttributeMethods(NativeWebRequest request, ModelAndViewContainer container)
		throws Exception {

	while (!this.modelMethods.isEmpty()) {
		InvocableHandlerMethod modelMethod = getNextModelMethod(container).getHandlerMethod();
		ModelAttribute ann = modelMethod.getMethodAnnotation(ModelAttribute.class);
		Assert.state(ann != null, "No ModelAttribute annotation");
		if (container.containsAttribute(ann.name())) {
			if (!ann.binding()) {
				container.setBindingDisabled(ann.name());
			}
			continue;
		}

		Object returnValue = modelMethod.invokeForRequest(request, container);
		if (!modelMethod.isVoid()){
			String returnValueName = getNameForReturnValue(returnValue, modelMethod.getReturnType());
			if (!ann.binding()) {
				container.setBindingDisabled(returnValueName);
			}
			if (!container.containsAttribute(returnValueName)) {
				container.addAttribute(returnValueName, returnValue);
			}
		}
	}
}
 
Example 7
Source File: DefaultResourceTransformerChain.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private ResourceTransformer getNext() {
	Assert.state(this.index <= this.transformers.size(),
			"Current index exceeds the number of configured ResourceTransformer's");

	if (this.index == (this.transformers.size() - 1)) {
		return null;
	}

	this.index++;
	return this.transformers.get(this.index);
}
 
Example 8
Source File: AbstractPollingMessageListenerContainer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a MessageConsumer for the given JMS Session,
 * registering a MessageListener for the specified listener.
 * @param session the JMS Session to work on
 * @return the MessageConsumer
 * @throws javax.jms.JMSException if thrown by JMS methods
 * @see #receiveAndExecute
 */
protected MessageConsumer createListenerConsumer(Session session) throws JMSException {
	Destination destination = getDestination();
	if (destination == null) {
		String destinationName = getDestinationName();
		Assert.state(destinationName != null, "No destination set");
		destination = resolveDestinationName(session, destinationName);
	}
	return createConsumer(session, destination);
}
 
Example 9
Source File: MockHttpServletResponse.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public PrintWriter getWriter() throws UnsupportedEncodingException {
	Assert.state(this.writerAccessAllowed, "Writer access not allowed");
	if (this.writer == null) {
		Writer targetWriter = (this.characterEncoding != null ?
				new OutputStreamWriter(this.content, this.characterEncoding) : new OutputStreamWriter(this.content));
		this.writer = new ResponsePrintWriter(targetWriter);
	}
	return this.writer;
}
 
Example 10
Source File: AbstractMessageEndpointFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * This {@code beforeDelivery} implementation starts a transaction,
 * if necessary, and exposes the endpoint ClassLoader as current
 * thread context ClassLoader.
 * <p>Note that the JCA 1.7 specification does not require a ResourceAdapter
 * to call this method before invoking the concrete endpoint. If this method
 * has not been called (check {@link #hasBeforeDeliveryBeenCalled()}), the
 * concrete endpoint method should call {@code beforeDelivery} and its
 * sibling {@link #afterDelivery()} explicitly, as part of its own processing.
 */
@Override
public void beforeDelivery(@Nullable Method method) throws ResourceException {
	this.beforeDeliveryCalled = true;
	Assert.state(this.transactionDelegate != null, "Not initialized");
	try {
		this.transactionDelegate.beginTransaction();
	}
	catch (Throwable ex) {
		throw new ApplicationServerInternalException("Failed to begin transaction", ex);
	}
	Thread currentThread = Thread.currentThread();
	this.previousContextClassLoader = currentThread.getContextClassLoader();
	currentThread.setContextClassLoader(getEndpointClassLoader());
}
 
Example 11
Source File: WebSocketServerSockJsSession.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public InetSocketAddress getLocalAddress() {
	Assert.state(this.webSocketSession != null, "WebSocketSession not yet initialized");
	return this.webSocketSession.getLocalAddress();
}
 
Example 12
Source File: RequestContextAwareTag.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Return the current RequestContext.
 */
protected final RequestContext getRequestContext() {
	Assert.state(this.requestContext != null, "No current RequestContext");
	return this.requestContext;
}
 
Example 13
Source File: CallMetaDataContext.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Build the call string based on configuration and meta-data information.
 * @return the call string to be used
 */
public String createCallString() {
	Assert.state(this.metaDataProvider != null, "No CallMetaDataProvider available");

	StringBuilder callString;
	int parameterCount = 0;
	String catalogNameToUse;
	String schemaNameToUse;

	// For Oracle where catalogs are not supported we need to reverse the schema name
	// and the catalog name since the catalog is used for the package name
	if (this.metaDataProvider.isSupportsSchemasInProcedureCalls() &&
			!this.metaDataProvider.isSupportsCatalogsInProcedureCalls()) {
		schemaNameToUse = this.metaDataProvider.catalogNameToUse(getCatalogName());
		catalogNameToUse = this.metaDataProvider.schemaNameToUse(getSchemaName());
	}
	else {
		catalogNameToUse = this.metaDataProvider.catalogNameToUse(getCatalogName());
		schemaNameToUse = this.metaDataProvider.schemaNameToUse(getSchemaName());
	}

	String procedureNameToUse = this.metaDataProvider.procedureNameToUse(getProcedureName());
	if (isFunction() || isReturnValueRequired()) {
		callString = new StringBuilder().append("{? = call ").
				append(StringUtils.hasLength(catalogNameToUse) ? catalogNameToUse + "." : "").
				append(StringUtils.hasLength(schemaNameToUse) ? schemaNameToUse + "." : "").
				append(procedureNameToUse).append("(");
		parameterCount = -1;
	}
	else {
		callString = new StringBuilder().append("{call ").
				append(StringUtils.hasLength(catalogNameToUse) ? catalogNameToUse + "." : "").
				append(StringUtils.hasLength(schemaNameToUse) ? schemaNameToUse + "." : "").
				append(procedureNameToUse).append("(");
	}

	for (SqlParameter parameter : this.callParameters) {
		if (!parameter.isResultsParameter()) {
			if (parameterCount > 0) {
				callString.append(", ");
			}
			if (parameterCount >= 0) {
				callString.append(createParameterBinding(parameter));
			}
			parameterCount++;
		}
	}
	callString.append(")}");

	return callString.toString();
}
 
Example 14
Source File: AsyncHttpAccessor.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Return the request factory that this accessor uses for obtaining {@link
 * org.springframework.http.client.ClientHttpRequest HttpRequests}.
 */
public org.springframework.http.client.AsyncClientHttpRequestFactory getAsyncRequestFactory() {
	Assert.state(this.asyncRequestFactory != null, "No AsyncClientHttpRequestFactory set");
	return this.asyncRequestFactory;
}
 
Example 15
Source File: BindTag.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Return the current BindStatus.
 */
private BindStatus getStatus() {
	Assert.state(this.status != null, "No current BindStatus");
	return this.status;
}
 
Example 16
Source File: MockPageContext.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public byte[] getContentAsByteArray() {
	Assert.state(this.response instanceof MockHttpServletResponse, "MockHttpServletResponse required");
	return ((MockHttpServletResponse) this.response).getContentAsByteArray();
}
 
Example 17
Source File: RequestHeaderMethodArgumentResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
	RequestHeader ann = parameter.getParameterAnnotation(RequestHeader.class);
	Assert.state(ann != null, "No RequestHeader annotation");
	return new RequestHeaderNamedValueInfo(ann);
}
 
Example 18
Source File: WebSocketClientSockJsSession.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public int getTextMessageSizeLimit() {
	Assert.state(this.webSocketSession != null, "WebSocketSession not yet initialized");
	return this.webSocketSession.getTextMessageSizeLimit();
}
 
Example 19
Source File: RestTemplateBuilder.java    From spring-vault with Apache License 2.0 3 votes vote down vote up
/**
 * Build a new {@link RestTemplate}. {@link VaultEndpoint} must be set.
 *
 * Applies also {@link ResponseErrorHandler} and {@link RestTemplateCustomizer} if
 * configured.
 * @return a new {@link RestTemplate}.
 */
public RestTemplate build() {

	Assert.state(this.endpointProvider != null, "VaultEndpointProvider must not be null");

	RestTemplate restTemplate = createTemplate();

	if (this.errorHandler != null) {
		restTemplate.setErrorHandler(this.errorHandler);
	}

	this.customizers.forEach(customizer -> customizer.customize(restTemplate));

	return restTemplate;
}
 
Example 20
Source File: ThreadPoolTaskScheduler.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Return the underlying ScheduledExecutorService for native access.
 * @return the underlying ScheduledExecutorService (never {@code null})
 * @throws IllegalStateException if the ThreadPoolTaskScheduler hasn't been initialized yet
 */
public ScheduledExecutorService getScheduledExecutor() throws IllegalStateException {
	Assert.state(this.scheduledExecutor != null, "ThreadPoolTaskScheduler not initialized");
	return this.scheduledExecutor;
}