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

The following examples show how to use org.springframework.util.Assert#isTrue() . 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
 * Retrieves the primary key from {@code acl_class}, creating a new row if needed and the
 * {@code allowCreate} property is {@code true}.
 * @param type to find or create an entry for (often the fully-qualified class name)
 * @param allowCreate true if creation is permitted if not found
 * @return the primary key or null if not found
protected AclClass createOrRetrieveClassPrimaryKey(String type, boolean allowCreate) {
    List<AclClass> classIds = aclDao.findAclClassList(type);

    if (!classIds.isEmpty()) {
        return classIds.get(0);

    if (allowCreate) {
        AclClass clazz = new AclClass();

                "Transaction must be running");
        return aclDao.createAclClass(clazz);

    return null;
Example 2
 * Retrieves and validates the storage unit for the specified business object data.
 * @param businessObjectDataEntity the business object data entity
 * @param storageEntity the storage entity
 * @return the storage unit entity
private StorageUnitEntity getStorageUnit(BusinessObjectDataEntity businessObjectDataEntity, StorageEntity storageEntity)
    // Retrieve and validate storage unit for the business object data.
    StorageUnitEntity storageUnitEntity = storageUnitDao.getStorageUnitByBusinessObjectDataAndStorage(businessObjectDataEntity, storageEntity);

    // Validate the storage unit.
    if (storageUnitEntity == null)
        throw new IllegalArgumentException(String
            .format("Business object data has no storage unit in \"%s\" storage. Business object data: {%s}", storageEntity.getName(),
        // Validate that storage unit is in "ARCHIVING" state.
        Assert.isTrue(StorageUnitStatusEntity.ARCHIVING.equals(storageUnitEntity.getStatus().getCode()), String.format(
            "Business object data is not currently being archived. " +
                "Storage unit in \"%s\" storage must have \"%s\" status, but it actually has \"%s\" status. Business object data: {%s}",
            storageEntity.getName(), StorageUnitStatusEntity.ARCHIVING, storageUnitEntity.getStatus().getCode(),

    return storageUnitEntity;
Example 3
Source Project: nfscan   File:    License: MIT License 5 votes vote down vote up
 * Validates whether of not electronic tax receipt's access keys are valid
 * @param accessKey a string containing a access key
 * @return true if valid false otherwise
public static boolean validateElectronicTaxReceiptAccessKey(String accessKey) {
    boolean ret = true;
    accessKey = removeNonNumeric(accessKey);
    DateFormat df = new SimpleDateFormat("yyMM");

    // Validate length
    if (accessKey.length() != 44)
        ret = false;

    // Validate numeric content
    if (!isNumeric(accessKey))
        ret = false;

    // Validate UF
    if (!Arrays.asList(Constants.IBGE_UF_CODES).contains(accessKey.substring(0, 2)))
        ret = false;

    // Validate date
    try {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(df.parse(accessKey.substring(2, 6)));
        Assert.isTrue(calendar.get(Calendar.MONTH) == Integer.parseInt(accessKey.substring(4, 6)) - 1);
    } catch (Exception e) {
        ret = false;

    // Validate CNPJ
    if (!validateCNPJ(accessKey.substring(6, 20)))
        ret = false;

    return ret;
Example 4
Source Project: haven-platform   File:    License: Apache License 2.0 5 votes vote down vote up
public Builder<T> checkEvery(long time, TimeUnit unit) {
    Assert.isTrue(time > 0, "time <= 0");
    Assert.notNull(unit, "TimeUnit can't be null");
    this.checkEveryTime = time;
    this.checkEveryUnit = unit;
    return this;
Example 5
Source Project: full-teaching   File:    License: Apache License 2.0 5 votes vote down vote up
 * Test method for {@link com.fullteaching.backend.user.User#getPicture()} 
 * and {@link com.fullteaching.backend.user.User#setPicture(java.lang.String)}.
public void setAndGetUserPictureTest() {
	User u = new User();
	Assert.isTrue(picture.equals(u.getPicture()), "SetAndGetUserPictureTest FAIL");
Example 6
 * Create a new {@link FixedTimeoutRefreshTrigger} to calculate execution times of
 * {@code timeout} before the {@link LoginToken} expires
 * @param timeout timeout value, non-negative long value.
 * @param timeUnit must not be {@literal null}.
public FixedTimeoutRefreshTrigger(long timeout, TimeUnit timeUnit) {

	Assert.isTrue(timeout >= 0, "Timeout duration must be greater or equal to zero");
	Assert.notNull(timeUnit, "TimeUnit must not be null");

	this.duration = Duration.ofMillis(timeUnit.toMillis(timeout));
	this.validTtlThreshold = Duration.ofMillis(timeUnit.toMillis(timeout) + 2000);
Example 7
Source Project: cf-butler   File:    License: Apache License 2.0 5 votes vote down vote up
public <T> T getOption(String key, Class<T> type) {
	Assert.isTrue(StringUtils.isNotBlank(key), "Option key must not be blank.");
	Object value = options.get(key);
	if (value == null) {
		return null;
	return type.cast(value);
Example 8
public static void validate(final LightminClientApplication lightminClientApplication) {
    Assert.notNull(lightminClientApplication, "LightminClientApplication must not be null");
    Assert.hasText(lightminClientApplication.getName(), "Name must not be null");
    Assert.hasText(lightminClientApplication.getHealthUrl(), "Health-URL must not be null");
    Assert.isTrue(validateUrl(lightminClientApplication.getHealthUrl()), "Health-URL is not valid");
                    || validateUrl(lightminClientApplication.getManagementUrl()), "URL is not valid");
                    || validateUrl(lightminClientApplication.getServiceUrl()), "URL is not valid");
Example 9
Source Project: cf-butler   File:    License: Apache License 2.0 5 votes vote down vote up
private Mono<String> getUsage(String usageType, String orgGuid, LocalDate start, LocalDate end) {
    Assert.hasText(orgGuid, "Global unique identifier for organization must not be blank or null!");
    Assert.notNull(start, "Start of date range must be specified!");
    Assert.notNull(end, "End of date range must be specified!");
    Assert.isTrue(end.isAfter(start), "Date range is invalid!");
    String uri = settings.getUsageDomain() + "/organizations/{orgGuid}/{usageType}?start={start}&end={end}";
    return getOauthToken()
            .flatMap(t -> webClient
                                .uri(uri, orgGuid, usageType, start.toString(), end.toString())
                                .header(HttpHeaders.AUTHORIZATION, t)
Example 10
public Acl readAclById(ObjectIdentity object, List<Sid> sids) throws NotFoundException {
    Map<ObjectIdentity, Acl> map = readAclsById(Arrays.asList(object), sids);
    Assert.isTrue(map.containsKey(object), "There should have been an Acl entry for ObjectIdentity " + object);

    return (Acl) map.get(object);
Example 11
Source Project: cola-cloud   File:    License: MIT License 5 votes vote down vote up
public SysTenant disable(Long id) {
    SysTenant sysTenant = this.selectById(id);
    Assert.isTrue(sysTenant.getStatus().equals(CommonConstant.TENANT_STATUS_ENABLED), "租户已禁用");
    return sysTenant;
Example 12
public MethodLinkBuilder<T> arg(int index, Object parameter) {
  Assert.isTrue(index >= 0, "Parameter index must be equal or greater than zero");

  Set<ParameterIndex> allParameters = new HashSet<ParameterIndex>(this.parameters);
  allParameters.add(new ParameterIndex(index, allParameters));

  return new SimpleMethodLinkBuilder<T>(this.linkFactory, this.methodName, allParameters,
Example 13
public void deleteExistSubscriptions() throws URISyntaxException, SubscriptionException, SubscriptionPersistenceException {
    SubscribeContext subscribeContext = createSubscribeContextTemperature();
    String subscriptionId = subscriptions.addSubscription(subscribeContext);
    UnsubscribeContext unsubscribeContext = new UnsubscribeContext(subscriptionId);
Example 14
public void setApplicationContext(ApplicationContext applicationContext) {
	Assert.isTrue(applicationContext instanceof ConfigurableApplicationContext,
			"ApplicationContext does not implement ConfigurableApplicationContext");
	this.applicationContext = (ConfigurableApplicationContext) applicationContext;
Example 15
public void validateParameters(List<Parameter> parameters)
    // This system job accepts no parameters.
    Assert.isTrue(org.springframework.util.CollectionUtils.isEmpty(parameters), String.format("\"%s\" system job does not except parameters.", JOB_NAME));
Example 16
public void testSendAndReceive() throws Exception {
	Binder binder = getBinder();
	BindingProperties outputBindingProperties = createProducerBindingProperties(
	DirectChannel moduleOutputChannel = createBindableChannel("output",

	BindingProperties inputBindingProperties = createConsumerBindingProperties(
	DirectChannel moduleInputChannel = createBindableChannel("input",

	Binding<MessageChannel> producerBinding = binder.bindProducer(
			String.format("foo%s0", getDestinationNameDelimiter()),
			moduleOutputChannel, outputBindingProperties.getProducer());
	Binding<MessageChannel> consumerBinding = binder.bindConsumer(
			String.format("foo%s0", getDestinationNameDelimiter()),
			"testSendAndReceive", moduleInputChannel,
	Message<?> message = MessageBuilder.withPayload("foo")
			.setHeader(MessageHeaders.CONTENT_TYPE, "text/plain").build();
	// Let the consumer actually bind to the producer before sending a msg

	CountDownLatch latch = new CountDownLatch(1);
	AtomicReference<Message<byte[]>> inboundMessageRef = new AtomicReference<Message<byte[]>>();
	moduleInputChannel.subscribe(message1 -> {
		try {
			inboundMessageRef.set((Message<byte[]>) message1);
		finally {

	Assert.isTrue(latch.await(5, TimeUnit.SECONDS), "Failed to receive message");

Example 17
protected static File validateDirectory(final File workingDirectory) {
	Assert.isTrue(workingDirectory != null && (workingDirectory.isDirectory() || workingDirectory.mkdirs()));
	return workingDirectory;
Example 18
Source Project: spring-analysis-note   File:    License: MIT License 4 votes vote down vote up
 * Deserialize the attributes of this session from a state object created by
 * {@link #serializeState()}.
 * @param state a representation of this session's serialized state
public void deserializeState(Serializable state) {
	Assert.isTrue(state instanceof Map, "Serialized state needs to be of type [java.util.Map]");
	this.attributes.putAll((Map<String, Object>) state);
Example 19
Source Project: dlock   File:    License: Apache License 2.0 3 votes vote down vote up
 * A free way to make the instance of {@link DistributedReentrantLock}
 * @param lockTypeStr
 * @param lockTarget
 * @param lease
 * @param leaseTimeUnit
 * @return
public Lock gen(String lockTypeStr, String lockTarget, int lease, TimeUnit leaseTimeUnit) {
    // pre-check
    Assert.isTrue(StringUtils.isNotEmpty(lockTypeStr), "lockTypeStr can't be empty!");
    Assert.isTrue(lease > 0, "leaseTime must greater than zero!");
    Assert.notNull(leaseTimeUnit, "leaseTimeUnit can't be null!");

    return getLockInstance(lockTypeStr, lockTarget, lease, leaseTimeUnit);
Example 20
 * Specify the number of concurrent consumers to create. Default is 1.
 * <p>Raising the number of concurrent consumers is recommendable in order
 * to scale the consumption of messages coming in from a queue. However,
 * note that any ordering guarantees are lost once multiple consumers are
 * registered. In general, stick with 1 consumer for low-volume queues.
 * <p><b>Do not raise the number of concurrent consumers for a topic.</b>
 * This would lead to concurrent consumption of the same message,
 * which is hardly ever desirable.
public void setConcurrentConsumers(int concurrentConsumers) {
	Assert.isTrue(concurrentConsumers > 0, "'concurrentConsumers' value must be at least 1 (one)");
	this.concurrentConsumers = concurrentConsumers;