org.springframework.lang.Nullable Java Examples

The following examples show how to use org.springframework.lang.Nullable. 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: AbstractUrlHandlerMapping.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Look up a handler instance for the given URL lookup path.
 * <p>Supports direct matches, e.g. a registered "/test" matches "/test",
 * and various path pattern matches, e.g. a registered "/t*" matches
 * both "/test" and "/team". For details, see the PathPattern class.
 * @param lookupPath the URL the handler is mapped to
 * @param exchange the current exchange
 * @return the associated handler instance, or {@code null} if not found
 * @see org.springframework.web.util.pattern.PathPattern
 */
@Nullable
protected Object lookupHandler(PathContainer lookupPath, ServerWebExchange exchange) throws Exception {

	List<PathPattern> matches = this.handlerMap.keySet().stream()
			.filter(key -> key.matches(lookupPath))
			.collect(Collectors.toList());

	if (matches.isEmpty()) {
		return null;
	}

	if (matches.size() > 1) {
		matches.sort(PathPattern.SPECIFICITY_COMPARATOR);
		if (logger.isTraceEnabled()) {
			logger.debug(exchange.getLogPrefix() + "Matching patterns " + matches);
		}
	}

	PathPattern pattern = matches.get(0);
	PathContainer pathWithinMapping = pattern.extractPathWithinPattern(lookupPath);
	return handleMatch(this.handlerMap.get(pattern), pattern, pathWithinMapping, exchange);
}
 
Example #2
Source File: JtaTransactionManager.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Find the JTA UserTransaction through a default JNDI lookup:
 * "java:comp/UserTransaction".
 * @return the JTA UserTransaction reference, or {@code null} if not found
 * @see #DEFAULT_USER_TRANSACTION_NAME
 */
@Nullable
protected UserTransaction findUserTransaction() {
	String jndiName = DEFAULT_USER_TRANSACTION_NAME;
	try {
		UserTransaction ut = getJndiTemplate().lookup(jndiName, UserTransaction.class);
		if (logger.isDebugEnabled()) {
			logger.debug("JTA UserTransaction found at default JNDI location [" + jndiName + "]");
		}
		this.userTransactionObtainedFromJndi = true;
		return ut;
	}
	catch (NamingException ex) {
		if (logger.isDebugEnabled()) {
			logger.debug("No JTA UserTransaction found at default JNDI location [" + jndiName + "]", ex);
		}
		return null;
	}
}
 
Example #3
Source File: RequestContextHolder.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Bind the given RequestAttributes to the current thread.
 * @param attributes the RequestAttributes to expose,
 * or {@code null} to reset the thread-bound context
 * @param inheritable whether to expose the RequestAttributes as inheritable
 * for child threads (using an {@link InheritableThreadLocal})
 */
public static void setRequestAttributes(@Nullable RequestAttributes attributes, boolean inheritable) {
	if (attributes == null) {
		resetRequestAttributes();
	}
	else {
		if (inheritable) {
			inheritableRequestAttributesHolder.set(attributes);
			requestAttributesHolder.remove();
		}
		else {
			requestAttributesHolder.set(attributes);
			inheritableRequestAttributesHolder.remove();
		}
	}
}
 
Example #4
Source File: MockServletContext.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@Nullable
public InputStream getResourceAsStream(String path) {
	Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
	if (!resource.exists()) {
		return null;
	}
	try {
		return resource.getInputStream();
	}
	catch (IOException ex) {
		if (logger.isWarnEnabled()) {
			logger.warn("Could not open InputStream for " + resource, ex);
		}
		return null;
	}
}
 
Example #5
Source File: RmiServiceExporter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Locate or create the RMI registry for this exporter.
 * @param registryHost the registry host to use (if this is specified,
 * no implicit creation of a RMI registry will happen)
 * @param registryPort the registry port to use
 * @param clientSocketFactory the RMI client socket factory for the registry (if any)
 * @param serverSocketFactory the RMI server socket factory for the registry (if any)
 * @return the RMI registry
 * @throws RemoteException if the registry couldn't be located or created
 */
protected Registry getRegistry(String registryHost, int registryPort,
		@Nullable RMIClientSocketFactory clientSocketFactory, @Nullable RMIServerSocketFactory serverSocketFactory)
		throws RemoteException {

	if (registryHost != null) {
		// Host explicitly specified: only lookup possible.
		if (logger.isDebugEnabled()) {
			logger.debug("Looking for RMI registry at port '" + registryPort + "' of host [" + registryHost + "]");
		}
		Registry reg = LocateRegistry.getRegistry(registryHost, registryPort, clientSocketFactory);
		testRegistry(reg);
		return reg;
	}

	else {
		return getRegistry(registryPort, clientSocketFactory, serverSocketFactory);
	}
}
 
Example #6
Source File: DefaultSingletonBeanRegistry.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Return the (raw) singleton object registered under the given name.
 * <p>Checks already instantiated singletons and also allows for an early
 * reference to a currently created singleton (resolving a circular reference).
 * @param beanName the name of the bean to look for
 * @param allowEarlyReference whether early references should be created or not
 * @return the registered singleton object, or {@code null} if none found
 */
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
	Object singletonObject = this.singletonObjects.get(beanName);
	if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
		synchronized (this.singletonObjects) {
			singletonObject = this.earlySingletonObjects.get(beanName);
			if (singletonObject == null && allowEarlyReference) {
				ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
				if (singletonFactory != null) {
					singletonObject = singletonFactory.getObject();
					this.earlySingletonObjects.put(beanName, singletonObject);
					this.singletonFactories.remove(beanName);
				}
			}
		}
	}
	return singletonObject;
}
 
Example #7
Source File: InternalSpelExpressionParser.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Nullable
private SpelNodeImpl eatPrimaryExpression() {
	SpelNodeImpl start = eatStartNode();  // always a start node
	List<SpelNodeImpl> nodes = null;
	SpelNodeImpl node = eatNode();
	while (node != null) {
		if (nodes == null) {
			nodes = new ArrayList<>(4);
			nodes.add(start);
		}
		nodes.add(node);
		node = eatNode();
	}
	if (start == null || nodes == null) {
		return start;
	}
	return new CompoundExpression(start.getStartPosition(), nodes.get(nodes.size() - 1).getEndPosition(),
			nodes.toArray(new SpelNodeImpl[0]));
}
 
Example #8
Source File: ObjectUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Return a String representation of the contents of the specified array.
 * <p>The String representation consists of a list of the array's elements,
 * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
 * by the characters {@code ", "} (a comma followed by a space). Returns
 * {@code "null"} if {@code array} is {@code null}.
 * @param array the array to build a String representation for
 * @return a String representation of {@code array}
 */
public static String nullSafeToString(@Nullable short[] array) {
	if (array == null) {
		return NULL_STRING;
	}
	int length = array.length;
	if (length == 0) {
		return EMPTY_ARRAY;
	}
	StringBuilder sb = new StringBuilder();
	for (int i = 0; i < length; i++) {
		if (i == 0) {
			sb.append(ARRAY_START);
		}
		else {
			sb.append(ARRAY_ELEMENT_SEPARATOR);
		}
		sb.append(array[i]);
	}
	sb.append(ARRAY_END);
	return sb.toString();
}
 
Example #9
Source File: CommonAnnotationBeanPostProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public ResourceElement(Member member, AnnotatedElement ae, @Nullable PropertyDescriptor pd) {
	super(member, pd);
	Resource resource = ae.getAnnotation(Resource.class);
	String resourceName = resource.name();
	Class<?> resourceType = resource.type();
	this.isDefaultName = !StringUtils.hasLength(resourceName);
	if (this.isDefaultName) {
		resourceName = this.member.getName();
		if (this.member instanceof Method && resourceName.startsWith("set") && resourceName.length() > 3) {
			resourceName = Introspector.decapitalize(resourceName.substring(3));
		}
	}
	else if (embeddedValueResolver != null) {
		resourceName = embeddedValueResolver.resolveStringValue(resourceName);
	}
	if (Object.class != resourceType) {
		checkResourceType(resourceType);
	}
	else {
		// No resource type specified... check field/method.
		resourceType = getResourceType();
	}
	this.name = (resourceName != null ? resourceName : "");
	this.lookupType = resourceType;
	String lookupValue = resource.lookup();
	this.mappedName = (StringUtils.hasLength(lookupValue) ? lookupValue : resource.mappedName());
	Lazy lazy = ae.getAnnotation(Lazy.class);
	this.lazyLookup = (lazy != null && lazy.value());
}
 
Example #10
Source File: AbstractMessageConverterMethodArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Constructor with converters and {@code Request~} and {@code ResponseBodyAdvice}.
 * @since 4.2
 */
public AbstractMessageConverterMethodArgumentResolver(List<HttpMessageConverter<?>> converters,
		@Nullable List<Object> requestResponseBodyAdvice) {

	Assert.notEmpty(converters, "'messageConverters' must not be empty");
	this.messageConverters = converters;
	this.allSupportedMediaTypes = getAllSupportedMediaTypes(converters);
	this.advice = new RequestResponseBodyAdviceChain(requestResponseBodyAdvice);
}
 
Example #11
Source File: DefaultPathContainer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public boolean equals(@Nullable Object other) {
	if (this == other) {
		return true;
	}
	if (other == null || getClass() != other.getClass()) {
		return false;
	}
	return this.path.equals(((DefaultPathContainer) other).path);
}
 
Example #12
Source File: RequestMappingHandlerAdapter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Configure the complete list of supported return value types thus
 * overriding handlers that would otherwise be configured by default.
 */
public void setReturnValueHandlers(@Nullable List<HandlerMethodReturnValueHandler> returnValueHandlers) {
	if (returnValueHandlers == null) {
		this.returnValueHandlers = null;
	}
	else {
		this.returnValueHandlers = new HandlerMethodReturnValueHandlerComposite();
		this.returnValueHandlers.addHandlers(returnValueHandlers);
	}
}
 
Example #13
Source File: StreamingResponseBodyReturnValueHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("resource")
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
	Assert.state(response != null, "No HttpServletResponse");
	ServerHttpResponse outputMessage = new ServletServerHttpResponse(response);

	if (returnValue instanceof ResponseEntity) {
		ResponseEntity<?> responseEntity = (ResponseEntity<?>) returnValue;
		response.setStatus(responseEntity.getStatusCodeValue());
		outputMessage.getHeaders().putAll(responseEntity.getHeaders());
		returnValue = responseEntity.getBody();
		if (returnValue == null) {
			mavContainer.setRequestHandled(true);
			outputMessage.flush();
			return;
		}
	}

	ServletRequest request = webRequest.getNativeRequest(ServletRequest.class);
	Assert.state(request != null, "No ServletRequest");
	ShallowEtagHeaderFilter.disableContentCaching(request);

	Assert.isInstanceOf(StreamingResponseBody.class, returnValue, "StreamingResponseBody expected");
	StreamingResponseBody streamingBody = (StreamingResponseBody) returnValue;

	Callable<Void> callable = new StreamingResponseBodyTask(outputMessage.getBody(), streamingBody);
	WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(callable, mavContainer);
}
 
Example #14
Source File: JsonPathExpectationsHelper.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
private Object assertExistsAndReturn(String content) {
	Object value = evaluateJsonPath(content);
	String reason = "No value at JSON path \"" + this.expression + "\"";
	AssertionErrors.assertTrue(reason, value != null);
	if (pathIsIndefinite() && value instanceof List) {
		AssertionErrors.assertTrue(reason, !((List<?>) value).isEmpty());
	}
	return value;
}
 
Example #15
Source File: LinkedCaseInsensitiveMap.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public V getOrDefault(Object key, V defaultValue) {
	if (key instanceof String) {
		String caseInsensitiveKey = this.caseInsensitiveKeys.get(convertKey((String) key));
		if (caseInsensitiveKey != null) {
			return this.targetMap.get(caseInsensitiveKey);
		}
	}
	return defaultValue;
}
 
Example #16
Source File: StompHeaders.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return the first header value for the given header name, if any.
 * @param headerName the header name
 * @return the first header value, or {@code null} if none
 */
@Override
@Nullable
public String getFirst(String headerName) {
	List<String> headerValues = this.headers.get(headerName);
	return headerValues != null ? headerValues.get(0) : null;
}
 
Example #17
Source File: RestTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
		Class<T> responseType) throws RestClientException {

	RequestCallback requestCallback = httpEntityCallback(requestEntity, responseType);
	ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
	return nonNull(execute(url, method, requestCallback, responseExtractor));
}
 
Example #18
Source File: RequestParamMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void contributeMethodArgument(MethodParameter parameter, @Nullable Object value,
		UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {

	Class<?> paramType = parameter.getNestedParameterType();
	if (Map.class.isAssignableFrom(paramType) || MultipartFile.class == paramType || Part.class == paramType) {
		return;
	}

	RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class);
	String name = (requestParam != null && StringUtils.hasLength(requestParam.name()) ?
			requestParam.name() : parameter.getParameterName());
	Assert.state(name != null, "Unresolvable parameter name");

	parameter = parameter.nestedIfOptional();
	if (value instanceof Optional) {
		value = ((Optional<?>) value).orElse(null);
	}

	if (value == null) {
		if (requestParam != null &&
				(!requestParam.required() || !requestParam.defaultValue().equals(ValueConstants.DEFAULT_NONE))) {
			return;
		}
		builder.queryParam(name);
	}
	else if (value instanceof Collection) {
		for (Object element : (Collection<?>) value) {
			element = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), element);
			builder.queryParam(name, element);
		}
	}
	else {
		builder.queryParam(name, formatUriValue(conversionService, new TypeDescriptor(parameter), value));
	}
}
 
Example #19
Source File: MultipartResolutionDelegate.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
public static MultipartRequest resolveMultipartRequest(NativeWebRequest webRequest) {
	MultipartRequest multipartRequest = webRequest.getNativeRequest(MultipartRequest.class);
	if (multipartRequest != null) {
		return multipartRequest;
	}
	HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
	if (servletRequest != null && isMultipartContent(servletRequest)) {
		return new StandardMultipartHttpServletRequest(servletRequest);
	}
	return null;
}
 
Example #20
Source File: CodeFlow.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Determine if the supplied descriptor is for a supported number type or boolean. The
 * compilation process only (currently) supports certain number types. These are
 * double, float, long and int.
 * @param descriptor the descriptor for a type
 * @return {@code true} if the descriptor is for a supported numeric type or boolean
 */
public static boolean isPrimitiveOrUnboxableSupportedNumberOrBoolean(@Nullable String descriptor) {
	if (descriptor == null) {
		return false;
	}
	if (isPrimitiveOrUnboxableSupportedNumber(descriptor)) {
		return true;
	}
	return ("Z".equals(descriptor) || descriptor.equals("Ljava/lang/Boolean"));
}
 
Example #21
Source File: AbstractErrors.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Transform the given field into its full path,
 * regarding the nested path of this instance.
 */
protected String fixedField(@Nullable String field) {
	if (StringUtils.hasLength(field)) {
		return getNestedPath() + canonicalFieldName(field);
	}
	else {
		String path = getNestedPath();
		return (path.endsWith(Errors.NESTED_PATH_SEPARATOR) ?
				path.substring(0, path.length() - NESTED_PATH_SEPARATOR.length()) : path);
	}
}
 
Example #22
Source File: ExpressionState.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
public Object lookupLocalVariable(String name) {
	for (VariableScope scope : initVariableScopes()) {
		if (scope.definesVariable(name)) {
			return scope.lookupVariable(name);
		}
	}
	return null;
}
 
Example #23
Source File: LocalStatelessSessionProxyFactoryBean.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
@Nullable
public Object getObject() {
	return this.proxy;
}
 
Example #24
Source File: ScriptTemplateConfigurer.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
@Nullable
public String[] getScripts() {
	return this.scripts;
}
 
Example #25
Source File: BeanDefinitionBuilder.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Add the supplied property value under the given name.
 */
public BeanDefinitionBuilder addPropertyValue(String name, @Nullable Object value) {
	this.beanDefinition.getPropertyValues().add(name, value);
	return this;
}
 
Example #26
Source File: JavaMailSenderImpl.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Return the mail protocol.
 */
@Nullable
public String getProtocol() {
	return this.protocol;
}
 
Example #27
Source File: JmsTemplate.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
@Nullable
public Message receive(Destination destination) throws JmsException {
	return receiveSelected(destination, null);
}
 
Example #28
Source File: DataSize.java    From java-technology-stack with MIT License 4 votes vote down vote up
private static DataUnit determineDataUnit(String suffix, @Nullable DataUnit defaultUnit) {
	DataUnit defaultUnitToUse = (defaultUnit != null ? defaultUnit : DataUnit.BYTES);
	return (StringUtils.hasLength(suffix) ? DataUnit.fromSuffix(suffix) : defaultUnitToUse);
}
 
Example #29
Source File: Target_AnnotationConfigUtils.java    From spring-graalvm-native with Apache License 2.0 4 votes vote down vote up
@Substitute
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(BeanDefinitionRegistry registry,
        @Nullable Object source) {
    return Collections.emptySet();
}
 
Example #30
Source File: ResourceRegionHttpMessageConverter.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public boolean canRead(Type type, @Nullable Class<?> contextClass, @Nullable MediaType mediaType) {
	return false;
}