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

The following examples show how to use org.springframework.util.Assert#notEmpty() . These examples are extracted from open source projects. 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 Project: alchemy   File: TableDescriptor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void validate() throws Exception {
    Assert.notEmpty(sources, "source不能为空");
    Assert.notEmpty(getSinkDescriptors(), "sink不能为空");
    for (SourceDescriptor sourceDescriptor : sources) {
        sourceDescriptor.validate();
    }
    for (SinkDescriptor sinkDescriptor : getSinkDescriptors()) {
        sinkDescriptor.validate();
    }
    if (CollectionUtils.isEmpty(udfs)) {
        return;
    }
    for (UdfDescriptor udfDescriptor : udfs) {
        udfDescriptor.validate();
    }
}
 
Example 2
@Override
protected void checkConnectParameters(String provider, String state, Map<String, String> connectParams) {
	super.checkConnectParameters(provider, state, connectParams);

	// Check connect parameters
	Assert.notEmpty(connectParams, "Connect parameters must not be empty");

	// Check principal
	String principalKey = config.getParam().getPrincipalName();
	Assert.hasText(connectParams.get(principalKey), String.format("'%s' must not be empty", principalKey));

	// PC-side browsers use agent redirection(QQ,sina)
	Assert.hasText(connectParams.get(config.getParam().getAgent()),
			String.format("'%s' must not be empty", config.getParam().getAgent()));

	// Check refreshUrl
	String refreshUrl = connectParams.get(config.getParam().getRefreshUrl());
	Assert.hasText(refreshUrl, String.format("'%s' must not be empty", config.getParam().getRefreshUrl()));
	try {
		new URI(refreshUrl);
	} catch (URISyntaxException e) {
		throw new IllegalArgumentException(String.format("Error syntax %s", config.getParam().getRefreshUrl()), e);
	}
}
 
Example 3
/**
 * 带显式定义的task的并行查询测试
 */
@Test
public void testParallelFetchWithExplicitDefTask() {
    QueryParam qp = new QueryParam();
    new TaskPair("deviceStatFetcher", DeviceRequest.build(qp));

    MultiResult ctx =
            parallelExePool.submit(
                    new TaskPair("explicitDefTask", DeviceRequest.build(qp)),
                    new TaskPair("deviceStatFetcher", DeviceRequest.build(qp)),
                    new TaskPair("deviceUvFetcher", DeviceRequest.build(qp)));

    List<DeviceViewItem> def = ctx.getResult("explicitDefTask");
    List<DeviceViewItem> stat = ctx.getResult("deviceStatFetcher");
    List<DeviceViewItem> uv = ctx.getResult("deviceUvFetcher");

    Assert.notEmpty(def);
    Assert.notEmpty(stat);
    Assert.notEmpty(uv);
    System.out.println(def);
}
 
Example 4
/**
 * 批量新增 使用pipeline方式
 */
@Override
public boolean add(final List<UserDTO> list) {
	Assert.notEmpty(list);
	boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
		@Override
		public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
			RedisSerializer<String> serializer = getRedisSerializer();
			for (UserDTO userDTO : list) {
				byte[] key = serializer.serialize(userDTO.getId());
				byte[] name = serializer.serialize(userDTO.getName());
				connection.setNX(key, name);
			}
			return true;
		}
	}, false, true);
	return result;
}
 
Example 5
Source Project: dubbox   File: SolrRealtimeGetRequest.java    License: Apache License 2.0 5 votes vote down vote up
public SolrRealtimeGetRequest(Collection<? extends Serializable> ids) {
	super(METHOD.GET, "/get");

	Assert.notEmpty(ids, "At least one 'id' is required for real time get request.");
	Assert.noNullElements(ids.toArray(), "Real time get request can't be made for 'null' id.");

	toStringIds(ids);
}
 
Example 6
/**
 * Constructor with converters and {@code Request~} and {@code ResponseBodyAdvice}.
 * @since 4.2
 */
public AbstractMessageConverterMethodArgumentResolver(List<HttpMessageConverter<?>> converters,
		List<Object> requestResponseBodyAdvice) {

	Assert.notEmpty(converters, "'messageConverters' must not be empty");
	this.messageConverters = converters;
	this.allSupportedMediaTypes = getAllSupportedMediaTypes(converters);
	this.advice = new RequestResponseBodyAdviceChain(requestResponseBodyAdvice);
}
 
Example 7
/**
 * Validate partionFilters and business format
 *
 * @param generateDdlRequest the generateDdlRequestWrapper object
 *
 * @return BusinessObjectFormat object
 */
public BusinessObjectFormat validatePartitionFiltersAndFormat(GenerateDdlRequestWrapper generateDdlRequest)
{
    // Validate that partition values passed in the list of partition filters do not contain '/' character.
    if (generateDdlRequest.isPartitioned && !CollectionUtils.isEmpty(generateDdlRequest.partitionFilters))
    {
        // Validate that partition values do not contain '/' characters.
        for (List<String> partitionFilter : generateDdlRequest.partitionFilters)
        {
            for (String partitionValue : partitionFilter)
            {
                Assert.doesNotContain(partitionValue, "/", String.format("Partition value \"%s\" can not contain a '/' character.", partitionValue));
            }
        }
    }

    // Get business object format model object to directly access schema columns and partitions.
    BusinessObjectFormat businessObjectFormat =
        businessObjectFormatHelper.createBusinessObjectFormatFromEntity(generateDdlRequest.businessObjectFormatEntity);

    // Validate that we have at least one column specified in the business object format schema.
    assertSchemaColumnsNotEmpty(businessObjectFormat, generateDdlRequest.businessObjectFormatEntity);

    if (generateDdlRequest.isPartitioned)
    {
        // Validate that we have at least one partition column specified in the business object format schema.
        Assert.notEmpty(businessObjectFormat.getSchema().getPartitions(), String.format("No schema partitions specified for business object format {%s}.",
            businessObjectFormatHelper.businessObjectFormatEntityAltKeyToString(generateDdlRequest.businessObjectFormatEntity)));

        // Validate that partition column names do not contain '/' characters.
        for (SchemaColumn partitionColumn : businessObjectFormat.getSchema().getPartitions())
        {
            Assert.doesNotContain(partitionColumn.getName(), "/", String
                .format("Partition column name \"%s\" can not contain a '/' character. Business object format: {%s}", partitionColumn.getName(),
                    businessObjectFormatHelper.businessObjectFormatEntityAltKeyToString(generateDdlRequest.businessObjectFormatEntity)));
        }
    }
    return businessObjectFormat;
}
 
Example 8
Source Project: super-cloudops   File: DefaultCumulator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void destroy(@NotNull List<String> factors) {
	Assert.notEmpty(factors, "factors must not be empty");

	factors.forEach(factor -> {
		try {
			cache.remove(new CacheKey(factor));
		} catch (Exception e) {
			log.error("", e);
		}
	});
}
 
Example 9
/**
 * 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 10
/**
     * 创建广告
     *
     * @param advertise 广告{@link Advertise}
     * @return
     */
    @RequestMapping(value = "create")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult create(@Valid Advertise advertise, BindingResult bindingResult,
                                @SessionAttribute(SESSION_MEMBER) AuthMember member,
                                @RequestParam(value = "pay[]") String[] pay, String jyPassword) throws Exception {
        MessageResult result = BindingResultUtil.validate(bindingResult);
        if (result != null) {
            return result;
        }
        Assert.notEmpty(pay, msService.getMessage("MISSING_PAY"));
        Assert.hasText(jyPassword, msService.getMessage("MISSING_JYPASSWORD"));
        Member member1 = memberService.findOne(member.getId());
        Assert.isTrue(member1.getIdNumber() != null, msService.getMessage("NO_REALNAME"));
//        if (allow == 1) {
            //allow是1的时候,必须是认证商家才能发布广告
        Assert.isTrue(member1.getMemberLevel().equals(MemberLevelEnum.IDENTIFICATION), msService.getMessage("NO_BUSINESS"));
//        }
        String mbPassword = member1.getJyPassword();
        Assert.hasText(mbPassword, msService.getMessage("NO_SET_JYPASSWORD"));
        Assert.isTrue(Md5.md5Digest(jyPassword + member1.getSalt()).toLowerCase().equals(mbPassword), msService.getMessage("ERROR_JYPASSWORD"));
        AdvertiseType advertiseType = advertise.getAdvertiseType();
        StringBuffer payMode = checkPayMode(pay, advertiseType, member1);
        advertise.setPayMode(payMode.toString());
        OtcCoin otcCoin = otcCoinService.findOne(advertise.getCoin().getId());
        checkAmount(advertiseType, advertise, otcCoin, member1);
        advertise.setLevel(AdvertiseLevel.ORDINARY);
        advertise.setRemainAmount(advertise.getNumber());
        Member mb = new Member();
        mb.setId(member.getId());
        advertise.setMember(mb);
        Advertise ad = advertiseService.saveAdvertise(advertise);
        if (ad != null) {
            return MessageResult.success(msService.getMessage("CREATE_SUCCESS"));
        } else {
            return MessageResult.error(msService.getMessage("CREATE_FAILED"));
        }
    }
 
Example 11
/**
 * Set flash attributes.
 * @param flashAttributes the flash attributes
 */
public MockHttpServletRequestBuilder flashAttrs(Map<String, Object> flashAttributes) {
	Assert.notEmpty(flashAttributes, "'flashAttributes' must not be empty");
	flashAttributes.forEach(this::flashAttr);
	return this;
}
 
Example 12
Source Project: linq   File: LinqTests.java    License: Apache License 2.0 4 votes vote down vote up
@Test
@Transactional
public void testFindAll() {
	Assert.notNull(JpaUtil.linq(User.class).list(), "Not Success.");
	User user = new User();
	user.setId(UUID.randomUUID().toString());
	user.setName("tom");
	User user2 = new User();
	user2.setName("kevin");
	user2.setId(UUID.randomUUID().toString());
	
	JpaUtil.persist(user);
	JpaUtil.persist(user2);
	
	Assert.notEmpty(JpaUtil.linq(User.class).list(), "Not Success.");
	
	Assert.isTrue(JpaUtil.linq(User.class).equal("name", "tom").list().size() == 1, "Not Success.");
	
	Pageable pageable = new PageRequest(0, 1);
	Page<User> page = JpaUtil.linq(User.class).paging(pageable);
	Assert.isTrue(page.getSize() == 1, "Not Success.");
	Assert.isTrue(page.getTotalElements() == 2, "Not Success.");
	Assert.isTrue(page.getTotalPages() == 2, "Not Success.");
	
	Pageable pageable2 = new PageRequest(0, 1, Direction.DESC, "name");
	Page<User> page2 = JpaUtil.linq(User.class).paging(pageable2);
	Assert.isTrue(page2.getContent().get(0).getName() == "tom", "Not Success.");
	Assert.isTrue(page2.getSize() == 1, "Not Success.");
	Assert.isTrue(page2.getTotalElements() == 2, "Not Success.");
	Assert.isTrue(page2.getTotalPages() == 2, "Not Success.");
	
	Pageable pageable3 = new PageRequest(0, 1, Direction.ASC, "name");
	Page<User> page3 = JpaUtil.linq(User.class).paging(pageable3);
	Assert.isTrue(page3.getContent().get(0).getName() == "kevin", "Not Success.");
	Assert.isTrue(page3.getSize() == 1, "Not Success.");
	Assert.isTrue(page3.getTotalElements() == 2, "Not Success.");
	Assert.isTrue(page3.getTotalPages() == 2, "Not Success.");
	
	Pageable pageable4 = new PageRequest(0, 1);
	Page<User> page4 = JpaUtil.linq(User.class).equal("name", "tom").paging(pageable4);
	Assert.isTrue(page4.getSize() == 1, "Not Success.");
	Assert.isTrue(page4.getTotalElements() == 1, "Not Success.");
	Assert.isTrue(page4.getTotalPages() == 1, "Not Success.");
	
	Pageable pageable5 = new PageRequest(0, 1, Direction.DESC, "name");
	Page<User> page5 = JpaUtil.linq(User.class).equal("name", "tom").paging(pageable5);
	Assert.isTrue(page5.getContent().get(0).getName() == "tom", "Not Success.");
	Assert.isTrue(page5.getSize() == 1, "Not Success.");
	Assert.isTrue(page5.getTotalElements() == 1, "Not Success.");
	Assert.isTrue(page5.getTotalPages() == 1, "Not Success.");
	
	Pageable pageable6 = new PageRequest(0, 1, Direction.DESC, "name");
	Page<User> page6 = JpaUtil.linq(User.class).equal("name", "tom").paging(pageable6);
	Assert.isTrue(page6.getContent().get(0).getName() == "tom", "Not Success.");
	Assert.isTrue(page6.getSize() == 1, "Not Success.");
	Assert.isTrue(page6.getTotalElements() == 1, "Not Success.");
	Assert.isTrue(page6.getTotalPages() == 1, "Not Success.");
	
	Page<User> page7 = JpaUtil.linq(User.class).equal("name", "tom").paging(null);
	Assert.isTrue(page7.getContent().get(0).getName() == "tom", "Not Success.");
	Assert.isTrue(page7.getSize() == 0, "Not Success.");
	Assert.isTrue(page7.getTotalElements() == 1, "Not Success.");
	Assert.isTrue(page7.getTotalPages() == 1, "Not Success.");
	
	JpaUtil.removeAllInBatch(User.class);
	
}
 
Example 13
/**
 * Build the {@link MergedContextConfiguration merged context configuration}
 * for the supplied {@link Class testClass}, context configuration attributes,
 * and parent context configuration.
 * @param testClass the test class for which the {@code MergedContextConfiguration}
 * should be built (must not be {@code null})
 * @param configAttributesList the list of context configuration attributes for the
 * specified test class, ordered <em>bottom-up</em> (i.e., as if we were
 * traversing up the class hierarchy); never {@code null} or empty
 * @param parentConfig the merged context configuration for the parent application
 * context in a context hierarchy, or {@code null} if there is no parent
 * @param cacheAwareContextLoaderDelegate the cache-aware context loader delegate to
 * be passed to the {@code MergedContextConfiguration} constructor
 * @param requireLocationsClassesOrInitializers whether locations, classes, or
 * initializers are required; typically {@code true} but may be set to {@code false}
 * if the configured loader supports empty configuration
 * @return the merged context configuration
 * @see #resolveContextLoader
 * @see ContextLoaderUtils#resolveContextConfigurationAttributes
 * @see SmartContextLoader#processContextConfiguration
 * @see ContextLoader#processLocations
 * @see ActiveProfilesUtils#resolveActiveProfiles
 * @see ApplicationContextInitializerUtils#resolveInitializerClasses
 * @see MergedContextConfiguration
 */
private MergedContextConfiguration buildMergedContextConfiguration(Class<?> testClass,
		List<ContextConfigurationAttributes> configAttributesList, @Nullable MergedContextConfiguration parentConfig,
		CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate,
		boolean requireLocationsClassesOrInitializers) {

	Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be null or empty");

	ContextLoader contextLoader = resolveContextLoader(testClass, configAttributesList);
	List<String> locations = new ArrayList<>();
	List<Class<?>> classes = new ArrayList<>();
	List<Class<?>> initializers = new ArrayList<>();

	for (ContextConfigurationAttributes configAttributes : configAttributesList) {
		if (logger.isTraceEnabled()) {
			logger.trace(String.format("Processing locations and classes for context configuration attributes %s",
					configAttributes));
		}
		if (contextLoader instanceof SmartContextLoader) {
			SmartContextLoader smartContextLoader = (SmartContextLoader) contextLoader;
			smartContextLoader.processContextConfiguration(configAttributes);
			locations.addAll(0, Arrays.asList(configAttributes.getLocations()));
			classes.addAll(0, Arrays.asList(configAttributes.getClasses()));
		}
		else {
			String[] processedLocations = contextLoader.processLocations(
					configAttributes.getDeclaringClass(), configAttributes.getLocations());
			locations.addAll(0, Arrays.asList(processedLocations));
			// Legacy ContextLoaders don't know how to process classes
		}
		initializers.addAll(0, Arrays.asList(configAttributes.getInitializers()));
		if (!configAttributes.isInheritLocations()) {
			break;
		}
	}

	Set<ContextCustomizer> contextCustomizers = getContextCustomizers(testClass,
			Collections.unmodifiableList(configAttributesList));

	Assert.state(!(requireLocationsClassesOrInitializers &&
			areAllEmpty(locations, classes, initializers, contextCustomizers)), () -> String.format(
			"%s was unable to detect defaults, and no ApplicationContextInitializers " +
			"or ContextCustomizers were declared for context configuration attributes %s",
			contextLoader.getClass().getSimpleName(), configAttributesList));

	MergedTestPropertySources mergedTestPropertySources =
			TestPropertySourceUtils.buildMergedTestPropertySources(testClass);
	MergedContextConfiguration mergedConfig = new MergedContextConfiguration(testClass,
			StringUtils.toStringArray(locations), ClassUtils.toClassArray(classes),
			ApplicationContextInitializerUtils.resolveInitializerClasses(configAttributesList),
			ActiveProfilesUtils.resolveActiveProfiles(testClass),
			mergedTestPropertySources.getLocations(),
			mergedTestPropertySources.getProperties(),
			contextCustomizers, contextLoader, cacheAwareContextLoaderDelegate, parentConfig);

	return processMergedContextConfiguration(mergedConfig);
}
 
Example 14
public ContextPathCompositeHandler(Map<String, ? extends HttpHandler> handlerMap) {
	Assert.notEmpty(handlerMap, "Handler map must not be empty");
	this.handlerMap = initHandlers(handlerMap);
}
 
Example 15
/**
 * Whether this converter should convert messages for which no content type
 * could be resolved through the configured
 * {@link org.springframework.messaging.converter.ContentTypeResolver}.
 * <p>A converter can configured to be strict only when a
 * {@link #setContentTypeResolver contentTypeResolver} is configured and the
 * list of {@link #getSupportedMimeTypes() supportedMimeTypes} is not be empty.
 * <p>When this flag is set to {@code true}, {@link #supportsMimeType(MessageHeaders)}
 * will return {@code false} if the {@link #setContentTypeResolver contentTypeResolver}
 * is not defined or if no content-type header is present.
 */
public void setStrictContentTypeMatch(boolean strictContentTypeMatch) {
	if (strictContentTypeMatch) {
		Assert.notEmpty(getSupportedMimeTypes(), "Strict match requires non-empty list of supported mime types");
		Assert.notNull(getContentTypeResolver(), "Strict match requires ContentTypeResolver");
	}
	this.strictContentTypeMatch = strictContentTypeMatch;
}
 
Example 16
/**
 * Construct a new StacktraceFingerprintingTaskRecoveryStrategy given the parser, and
 * the expected exception class to be thrown for sample fragments of a task definition
 * that is to be parsed.
 *
 * @param exceptionClass the expected exception that results from parsing the sample
 * fragment stream definitions. Stack frames from the thrown exception are used to
 * store the fingerprint of this exception thrown by the parser.
 * @param samples the sample fragments of task definitions.
 */
public StacktraceFingerprintingTaskRecoveryStrategy(Class<E> exceptionClass, String... samples) {
	Assert.notNull(exceptionClass, "exceptionClass should not be null");
	Assert.notEmpty(samples, "samples should not be null or empty");
	this.exceptionClass = exceptionClass;
	initFingerprints(samples);
}
 
Example 17
/**
 * Register one or more annotated classes to be processed.
 * <p>Note that {@link #refresh()} must be called in order for the context
 * to fully process the new classes.
 * @param annotatedClasses one or more annotated classes,
 * e.g. {@link org.springframework.context.annotation.Configuration @Configuration} classes
 * @see #scan(String...)
 * @see #loadBeanDefinitions(DefaultListableBeanFactory)
 * @see #setConfigLocation(String)
 * @see #refresh()
 */
public void register(Class<?>... annotatedClasses) {
	Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
	Collections.addAll(this.annotatedClasses, annotatedClasses);
}
 
Example 18
Source Project: herd   File: Hive13DdlGenerator.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Asserts that there exists at least one column specified in the business object format schema.
 *
 * @param businessObjectFormat The {@link BusinessObjectFormat} containing schema columns.
 * @param businessObjectFormatEntity The entity used to generate the error message.
 */
private void assertSchemaColumnsNotEmpty(BusinessObjectFormat businessObjectFormat, BusinessObjectFormatEntity businessObjectFormatEntity)
{
    Assert.notEmpty(businessObjectFormat.getSchema().getColumns(), String.format("No schema columns specified for business object format {%s}.",
        businessObjectFormatHelper.businessObjectFormatEntityAltKeyToString(businessObjectFormatEntity)));
}
 
Example 19
/**
 * Return a {@code RequestPredicate} that tests if the request's
 * {@linkplain ServerRequest.Headers#accept() accept} header is
 * {@linkplain MediaType#isCompatibleWith(MediaType) compatible} with any of the given media types.
 * @param mediaTypes the media types to match the request's accept header against
 * @return a predicate that tests the request's accept header against the given media types
 */
public static RequestPredicate accept(MediaType... mediaTypes) {
	Assert.notEmpty(mediaTypes, "'mediaTypes' must not be empty");
	return new AcceptPredicate(mediaTypes);
}
 
Example 20
/**
 * Perform a scan within the specified base packages.
 * <p>Note that {@link #refresh()} must be called in order for the context
 * to fully process the new classes.
 * @param basePackages the packages to check for annotated classes
 * @see #loadBeanDefinitions(DefaultListableBeanFactory)
 * @see #register(Class...)
 * @see #setConfigLocation(String)
 * @see #refresh()
 */
public void scan(String... basePackages) {
	Assert.notEmpty(basePackages, "At least one base package must be specified");
	Collections.addAll(this.basePackages, basePackages);
}