Java Code Examples for org.springframework.util.Assert#notNull()
The following examples show how to use
org.springframework.util.Assert#notNull() .
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: HBaseTemplate.java From dew with Apache License 2.0 | 6 votes |
/** * To action tables by tableName. * * @param tableName the target table * @param action table object action * @return the result object of the callback action, or null */ @Override public <T> T execute(String tableName, TableCallback<T> action) throws IOException { Assert.notNull(action, "Callback object must not be null"); Assert.notNull(tableName, "No table specified"); Table table = null; try { table = this.getConnection().getTable(TableName.valueOf(tableName)); return action.doInTable(table); } catch (Throwable throwable) { throw new HBaseRunTimeException(throwable); } finally { if (null != table) { table.close(); } } }
Example 2
Source File: ValidationUtils.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * Invoke the given {@link Validator}/{@link SmartValidator} for the supplied object and * {@link Errors} instance. * @param validator the {@code Validator} to be invoked (must not be {@code null}) * @param obj the object to bind the parameters to * @param errors the {@link Errors} instance that should store the errors (must not be {@code null}) * @param validationHints one or more hint objects to be passed to the validation engine * @throws IllegalArgumentException if either of the {@code Validator} or {@code Errors} arguments is * {@code null}, or if the supplied {@code Validator} does not {@link Validator#supports(Class) support} * the validation of the supplied object's type */ public static void invokeValidator(Validator validator, Object obj, Errors errors, Object... validationHints) { Assert.notNull(validator, "Validator must not be null"); Assert.notNull(errors, "Errors object must not be null"); if (logger.isDebugEnabled()) { logger.debug("Invoking validator [" + validator + "]"); } if (obj != null && !validator.supports(obj.getClass())) { throw new IllegalArgumentException( "Validator [" + validator.getClass() + "] does not support [" + obj.getClass() + "]"); } if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(obj, errors, validationHints); } else { validator.validate(obj, errors); } if (logger.isDebugEnabled()) { if (errors.hasErrors()) { logger.debug("Validator found " + errors.getErrorCount() + " errors"); } else { logger.debug("Validator found no errors"); } } }
Example 3
Source File: AsyncRestTemplate.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Create a new instance of the {@code AsyncRestTemplate} using the given * {@link AsyncTaskExecutor}. * <p>This constructor uses a {@link SimpleClientHttpRequestFactory} in combination * with the given {@code AsyncTaskExecutor} for asynchronous execution. */ public AsyncRestTemplate(AsyncListenableTaskExecutor taskExecutor) { Assert.notNull(taskExecutor, "AsyncTaskExecutor must not be null"); SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setTaskExecutor(taskExecutor); this.syncTemplate = new RestTemplate(requestFactory); setAsyncRequestFactory(requestFactory); }
Example 4
Source File: ChatUnitaryTest.java From full-teaching with Apache License 2.0 | 5 votes |
@Test public void addUser2ChatTest() { Chat ch = new Chat (chatManager, chat_name, executor, teacher_name); Assert.notNull(ch); WebSocketChatUser wschu = new WebSocketChatUser(session, user_name, color); WebSocketChatUser wscht = new WebSocketChatUser(session, teacher_name, "teacherColor"); ch.addUser(wschu); ch.addUser(wscht); Assert.isTrue(ch.getUser(user_name).equals(wschu)); Assert.isTrue(ch.getUser(teacher_name).equals(wscht)); Assert.isTrue(ch.getUsers().size()==2); Assert.isTrue(chat_name.equals(ch.getName())); }
Example 5
Source File: LoginTokenAdapter.java From spring-vault with Apache License 2.0 | 5 votes |
/** * Create a new {@link LoginTokenAdapter} given {@link ClientAuthentication} to * decorate and {@link RestOperations}. * @param delegate must not be {@literal null}. * @param restOperations must not be {@literal null}. */ public LoginTokenAdapter(ClientAuthentication delegate, RestOperations restOperations) { Assert.notNull(delegate, "ClientAuthentication delegate must not be null"); Assert.notNull(restOperations, "RestOperations must not be null"); this.delegate = delegate; this.restOperations = restOperations; }
Example 6
Source File: DefaultRowMapperWorkbookReader.java From onetwo with Apache License 2.0 | 5 votes |
public Map<String, List<Object>> readData(File file){ Assert.notNull(file, "file can not be null"); try { if(!file.exists()){ throw new FileNotFoundException("文件不存在:" + file.getPath()); } Workbook workbook = createWorkbook(file); return readData(workbook); } catch (Exception e) { throw ExcelUtils.wrapAsUnCheckedException("read excel file error.", e); } }
Example 7
Source File: ReleaseCommands.java From spring-data-dev-tools with Apache License 2.0 | 5 votes |
/** * Concludes the release of the given {@link TrainIteration}. * * @param iteration * @throws Exception */ @CliCommand(value = "release conclude") public void conclude(@CliOption(key = "", mandatory = true) TrainIteration iteration) throws Exception { Assert.notNull(iteration, "Train iteration must not be null!"); build.prepareVersions(iteration, Phase.CLEANUP); git.commit(iteration, "Prepare next development iteration."); // Prepare master branch build.updateProjectDescriptors(iteration, Phase.CLEANUP); git.commit(iteration, "After release cleanups."); // Tag release git.tagRelease(iteration); // Prepare maintenance branches if (iteration.getIteration().isGAIteration()) { // Create bugfix branches git.createMaintenanceBranches(iteration); // Set project version to maintenance once build.prepareVersions(iteration, Phase.MAINTENANCE); git.commit(iteration, "Prepare next development iteration."); // Update inter-project dependencies and repositories build.updateProjectDescriptors(iteration, Phase.MAINTENANCE); git.commit(iteration, "After release cleanups."); // Back to master branch git.checkout(iteration); } }
Example 8
Source File: PostServiceImpl.java From halo with GNU General Public License v3.0 | 5 votes |
private PostDetailVO createOrUpdate(@NonNull Post post, Set<Integer> tagIds, Set<Integer> categoryIds, Set<PostMeta> metas) { Assert.notNull(post, "Post param must not be null"); // Create or update post post = super.createOrUpdateBy(post); postTagService.removeByPostId(post.getId()); postCategoryService.removeByPostId(post.getId()); // List all tags List<Tag> tags = tagService.listAllByIds(tagIds); // List all categories List<Category> categories = categoryService.listAllByIds(categoryIds); // Create post tags List<PostTag> postTags = postTagService.mergeOrCreateByIfAbsent(post.getId(), ServiceUtils.fetchProperty(tags, Tag::getId)); log.debug("Created post tags: [{}]", postTags); // Create post categories List<PostCategory> postCategories = postCategoryService .mergeOrCreateByIfAbsent(post.getId(), ServiceUtils.fetchProperty(categories, Category::getId)); log.debug("Created post categories: [{}]", postCategories); // Create post meta data List<PostMeta> postMetaList = postMetaService .createOrUpdateByPostId(post.getId(), metas); log.debug("Created post metas: [{}]", postMetaList); // Convert to post detail vo return convertTo(post, tags, categories, postMetaList); }
Example 9
Source File: KeyGeneratorAdapter.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Create an instance used to wrap the specified {@link javax.cache.annotation.CacheKeyGenerator}. */ public KeyGeneratorAdapter(JCacheOperationSource cacheOperationSource, CacheKeyGenerator target) { Assert.notNull(cacheOperationSource, "cacheOperationSource must not be null."); Assert.notNull(target, "KeyGenerator must not be null"); this.cacheOperationSource = cacheOperationSource; this.cacheKeyGenerator = target; }
Example 10
Source File: MockPageContext.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public void removeAttribute(String name) { Assert.notNull(name, "Attribute name must not be null"); this.removeAttribute(name, PageContext.PAGE_SCOPE); this.removeAttribute(name, PageContext.REQUEST_SCOPE); this.removeAttribute(name, PageContext.SESSION_SCOPE); this.removeAttribute(name, PageContext.APPLICATION_SCOPE); }
Example 11
Source File: ContactServiceImpl.java From super-cloudops with Apache License 2.0 | 5 votes |
@Override public void del(Integer id) { Assert.notNull(id, "id can not be null"); Contact contact = new Contact(); contact.preUpdate(); contact.setId(id); contact.setDelFlag(1); contactDao.updateByPrimaryKeySelective(contact); }
Example 12
Source File: SdkCertTest.java From WeBASE-Front with Apache License 2.0 | 4 votes |
@Test public void testNodeCertsService() { List<String> sdkList = frontCertService.getNodeCerts(); Assert.notNull(sdkList, "load sdk crt error"); sdkList.stream().forEach(c -> System.out.println(c)); }
Example 13
Source File: DynamicBeanValidatorFactory.java From hsweb-framework with Apache License 2.0 | 4 votes |
@Override public Validator createValidator(TableMetaData tableMetaData) { Proxy<MapBean> proxy = Proxy.create(MapBean.class); StringBuilder keySet = new StringBuilder("public java.util.Set keySet(){\n return new java.util.HashSet(java.util.Arrays.asList(new String[]{"); int index = 0; for (ColumnMetaData column : tableMetaData.getColumns()) { String propertyName = column.getAlias(); Class type = column.getJavaType(); String typeName = type.getName(); if (index++ > 0) { keySet.append(","); } keySet.append("\"") .append(propertyName) .append("\""); proxy.custom(ctClass -> { try { CtField ctField = CtField.make("private " + type.getName() + " " + propertyName + ";", ctClass); List<JSR303AnnotationInfo> jsr303 = createValidatorAnnotation(column.getValidator()); //添加注解 if (!CollectionUtils.isEmpty(jsr303)) { ConstPool constPool = ctClass.getClassFile().getConstPool(); AnnotationsAttribute attributeInfo = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag); for (JSR303AnnotationInfo jsr303AnnotationInfo : jsr303) { Class<? extends java.lang.annotation.Annotation> jsr303Ann = jsr303AnnotationInfo.getAnnotation(); Annotation ann = new javassist.bytecode.annotation.Annotation(jsr303Ann.getName(), constPool); if (!CollectionUtils.isEmpty(jsr303AnnotationInfo.getProperties())) { jsr303AnnotationInfo.getProperties().forEach((key, value) -> { MemberValue memberValue = createMemberValue(value, constPool); if (memberValue != null) { ann.addMemberValue(key, memberValue); } }); } attributeInfo.addAnnotation(ann); } ctField.getFieldInfo().addAttribute(attributeInfo); } ctClass.addField(ctField); } catch (Exception e) { throw new RuntimeException(e); } }); proxy.addMethod("public void set" + StringUtils.toUpperCaseFirstOne(propertyName) + "(" + typeName + " " + propertyName + "){\n" + "this." + propertyName + "=" + propertyName + ";\n" + "\n};"); proxy.addMethod("public " + typeName + " get" + StringUtils.toUpperCaseFirstOne(propertyName) + "(){\n" + "return this." + propertyName + ";\n" + "\n};"); } keySet.append("}));\n}"); proxy.addMethod(keySet.toString()); proxy.addMethod(createSetPropertyCode(tableMetaData)); proxy.addMethod(createGetPropertyCode(tableMetaData)); //尝试一下能否创建实例 MapBean mapBean = proxy.newInstance(); Assert.notNull(mapBean, "创建验证器失败!"); return new DynamicBeanValidator(proxy::newInstance); }
Example 14
Source File: SimpleSearchQueryBuilder.java From onetwo with Apache License 2.0 | 4 votes |
public <T extends QueryBuilder> T mustNot(T queryBuilder){ Assert.notNull(queryBuilder); // boolQuery.mustNot(queryBuilder); addToBoolQuery(()->boolQuery.mustNot(queryBuilder)); return queryBuilder; }
Example 15
Source File: DivideFunction.java From dubbox with Apache License 2.0 | 4 votes |
public Builder(Object dividend) { Assert.notNull(dividend, "Dividend must not be 'null'"); this.dividend = dividend; }
Example 16
Source File: ReflectiveLoadTimeWeaver.java From lams with GNU General Public License v2.0 | 4 votes |
@Override public void addTransformer(ClassFileTransformer transformer) { Assert.notNull(transformer, "Transformer must not be null"); ReflectionUtils.invokeMethod(this.addTransformerMethod, this.classLoader, transformer); }
Example 17
Source File: ExceptionDepthComparator.java From spring-analysis-note with MIT License | 4 votes |
/** * Create a new ExceptionDepthComparator for the given exception. * @param exception the target exception to compare to when sorting by depth */ public ExceptionDepthComparator(Throwable exception) { Assert.notNull(exception, "Target exception must not be null"); this.targetException = exception.getClass(); }
Example 18
Source File: GenericTypeResolver.java From spring4-understanding with Apache License 2.0 | 4 votes |
/** * Determine the target type for the generic return type of the given * <em>generic method</em>, where formal type variables are declared on * the given method itself. * <p>For example, given a factory method with the following signature, * if {@code resolveReturnTypeForGenericMethod()} is invoked with the reflected * method for {@code creatProxy()} and an {@code Object[]} array containing * {@code MyService.class}, {@code resolveReturnTypeForGenericMethod()} will * infer that the target return type is {@code MyService}. * <pre class="code">{@code public static <T> T createProxy(Class<T> clazz)}</pre> * <h4>Possible Return Values</h4> * <ul> * <li>the target return type, if it can be inferred</li> * <li>the {@linkplain Method#getReturnType() standard return type}, if * the given {@code method} does not declare any {@linkplain * Method#getTypeParameters() formal type variables}</li> * <li>the {@linkplain Method#getReturnType() standard return type}, if the * target return type cannot be inferred (e.g., due to type erasure)</li> * <li>{@code null}, if the length of the given arguments array is shorter * than the length of the {@linkplain * Method#getGenericParameterTypes() formal argument list} for the given * method</li> * </ul> * @param method the method to introspect, never {@code null} * @param args the arguments that will be supplied to the method when it is * invoked (never {@code null}) * @param classLoader the ClassLoader to resolve class names against, if necessary * (may be {@code null}) * @return the resolved target return type, the standard return type, or {@code null} * @since 3.2.5 * @see #resolveReturnType */ public static Class<?> resolveReturnTypeForGenericMethod(Method method, Object[] args, ClassLoader classLoader) { Assert.notNull(method, "Method must not be null"); Assert.notNull(args, "Argument array must not be null"); TypeVariable<Method>[] declaredTypeVariables = method.getTypeParameters(); Type genericReturnType = method.getGenericReturnType(); Type[] methodArgumentTypes = method.getGenericParameterTypes(); // No declared type variables to inspect, so just return the standard return type. if (declaredTypeVariables.length == 0) { return method.getReturnType(); } // The supplied argument list is too short for the method's signature, so // return null, since such a method invocation would fail. if (args.length < methodArgumentTypes.length) { return null; } // Ensure that the type variable (e.g., T) is declared directly on the method // itself (e.g., via <T>), not on the enclosing class or interface. boolean locallyDeclaredTypeVariableMatchesReturnType = false; for (TypeVariable<Method> currentTypeVariable : declaredTypeVariables) { if (currentTypeVariable.equals(genericReturnType)) { locallyDeclaredTypeVariableMatchesReturnType = true; break; } } if (locallyDeclaredTypeVariableMatchesReturnType) { for (int i = 0; i < methodArgumentTypes.length; i++) { Type currentMethodArgumentType = methodArgumentTypes[i]; if (currentMethodArgumentType.equals(genericReturnType)) { return args[i].getClass(); } if (currentMethodArgumentType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) currentMethodArgumentType; Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (Type typeArg : actualTypeArguments) { if (typeArg.equals(genericReturnType)) { Object arg = args[i]; if (arg instanceof Class) { return (Class<?>) arg; } else if (arg instanceof String && classLoader != null) { try { return classLoader.loadClass((String) arg); } catch (ClassNotFoundException ex) { throw new IllegalStateException( "Could not resolve specific class name argument [" + arg + "]", ex); } } else { // Consider adding logic to determine the class of the typeArg, if possible. // For now, just fall back... return method.getReturnType(); } } } } } } // Fall back... return method.getReturnType(); }
Example 19
Source File: PubSubSubscriberTemplate.java From spring-cloud-gcp with Apache License 2.0 | 2 votes |
/** * Set a custom {@link Executor} to control the threads that process * the responses of the asynchronous pull callback operations. * * @param asyncPullExecutor the executor to set */ public void setAsyncPullExecutor(Executor asyncPullExecutor) { Assert.notNull(asyncPullExecutor, "asyncPullExecutor can't be null."); this.asyncPullExecutor = asyncPullExecutor; }
Example 20
Source File: ResolvableType.java From spring4-understanding with Apache License 2.0 | 2 votes |
/** * Return a {@link ResolvableType} for the specified {@link Class} * with a given implementation. * For example: {@code ResolvableType.forClass(List.class, MyArrayList.class)}. * @param sourceClass the source class (must not be {@code null} * @param implementationClass the implementation class * @return a {@link ResolvableType} for the specified class backed by the given * implementation class * @see #forClass(Class) * @see #forClassWithGenerics(Class, Class...) */ public static ResolvableType forClass(Class<?> sourceClass, Class<?> implementationClass) { Assert.notNull(sourceClass, "Source class must not be null"); ResolvableType asType = forType(implementationClass).as(sourceClass); return (asType == NONE ? forType(sourceClass) : asType); }