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

The following examples show how to use org.springframework.util.Assert#isTrue() . 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: JpaMutableAclService.java    From Spring-Security-Third-Edition with MIT License 7 votes vote down vote up
/**
 * 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();
        clazz.setClazz(type);

        Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(),
                "Transaction must be running");
        return aclDao.createAclClass(clazz);
    }

    return null;
}
 
Example 2
Source File: BusinessObjectDataRetryStoragePolicyTransitionHelper.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * 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(),
                businessObjectDataHelper.businessObjectDataEntityAltKeyToString(businessObjectDataEntity)));
    }
    else
    {
        // 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(),
            businessObjectDataHelper.businessObjectDataEntityAltKeyToString(businessObjectDataEntity)));
    }

    return storageUnitEntity;
}
 
Example 3
Source File: StringUtils.java    From nfscan with 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.setLenient(false);
        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 File: SubscriptionsTest.java    From fiware-cepheus with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void deleteExistSubscriptions() throws URISyntaxException, SubscriptionException, SubscriptionPersistenceException {
    SubscribeContext subscribeContext = createSubscribeContextTemperature();
    String subscriptionId = subscriptions.addSubscription(subscribeContext);
    Assert.isTrue(subscriptionsRepository.getAllSubscriptions().size()==1);
    UnsubscribeContext unsubscribeContext = new UnsubscribeContext(subscriptionId);
    assertTrue(subscriptions.deleteSubscription(unsubscribeContext));
    Assert.isTrue(subscriptionsRepository.getAllSubscriptions().size()==0);
}
 
Example 5
Source File: SimpleMethodLinkBuilder.java    From springlets with Apache License 2.0 5 votes vote down vote up
@Override
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,
      this.pathVariables);
}
 
Example 6
Source File: SysTenantServiceImpl.java    From cola-cloud with MIT License 5 votes vote down vote up
@Override
public SysTenant disable(Long id) {
    SysTenant sysTenant = this.selectById(id);
    Assert.notNull(sysTenant,"租户不存在");
    Assert.isTrue(sysTenant.getStatus().equals(CommonConstant.TENANT_STATUS_ENABLED), "租户已禁用");
    sysTenant.setStatus(CommonConstant.TENANT_STATUS_DISABLE);
    this.updateById(sysTenant);
    return sysTenant;
}
 
Example 7
Source File: JpaMutableAclService.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
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 8
Source File: UsageService.java    From cf-butler with 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
                            .get()
                                .uri(uri, orgGuid, usageType, start.toString(), end.toString())
                                .header(HttpHeaders.AUTHORIZATION, t)
                                    .retrieve()
                                        .bodyToMono(String.class));
}
 
Example 9
Source File: LightminApplicationValidator.java    From spring-batch-lightmin with Apache License 2.0 5 votes vote down vote up
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");
    Assert.isTrue(
            StringUtils.isEmpty(lightminClientApplication.getManagementUrl())
                    || validateUrl(lightminClientApplication.getManagementUrl()), "URL is not valid");
    Assert.isTrue(
            StringUtils.isEmpty(lightminClientApplication.getServiceUrl())
                    || validateUrl(lightminClientApplication.getServiceUrl()), "URL is not valid");
}
 
Example 10
Source File: ServiceInstancePolicy.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
@JsonIgnore
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 11
Source File: LifecycleAwareSessionManagerSupport.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * 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 12
Source File: UserUnitaryTest.java    From full-teaching with 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)}.
 */
@Test
public void setAndGetUserPictureTest() {
	User u = new User();
	u.setPicture(picture);
	Assert.isTrue(picture.equals(u.getPicture()), "SetAndGetUserPictureTest FAIL");
}
 
Example 13
Source File: LimitCheckers.java    From haven-platform with 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 14
Source File: AbstractBinderTests.java    From spring-cloud-stream with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test
public void testSendAndReceive() throws Exception {
	Binder binder = getBinder();
	BindingProperties outputBindingProperties = createProducerBindingProperties(
			createProducerProperties());
	DirectChannel moduleOutputChannel = createBindableChannel("output",
			outputBindingProperties);

	BindingProperties inputBindingProperties = createConsumerBindingProperties(
			createConsumerProperties());
	DirectChannel moduleInputChannel = createBindableChannel("input",
			inputBindingProperties);

	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,
			inputBindingProperties.getConsumer());
	Message<?> message = MessageBuilder.withPayload("foo")
			.setHeader(MessageHeaders.CONTENT_TYPE, "text/plain").build();
	// Let the consumer actually bind to the producer before sending a msg
	binderBindUnbindLatency();

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

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

	assertThat(inboundMessageRef.get().getPayload()).isEqualTo("foo".getBytes());
	assertThat(inboundMessageRef.get().getHeaders().get(MessageHeaders.CONTENT_TYPE)
			.toString()).isEqualTo("text/plain");
	producerBinding.unbind();
	consumerBinding.unbind();
}
 
Example 15
Source File: RelationalTableSchemaUpdateSystemJob.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
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
Source File: ProcessExecutor.java    From spring-cloud-stream-app-starters with Apache License 2.0 4 votes vote down vote up
protected static File validateDirectory(final File workingDirectory) {
	Assert.isTrue(workingDirectory != null && (workingDirectory.isDirectory() || workingDirectory.mkdirs()));
	return workingDirectory;
}
 
Example 17
Source File: EventListenerMethodProcessor.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
	Assert.isTrue(applicationContext instanceof ConfigurableApplicationContext,
			"ApplicationContext does not implement ConfigurableApplicationContext");
	this.applicationContext = (ConfigurableApplicationContext) applicationContext;
}
 
Example 18
Source File: MockHttpSession.java    From spring-analysis-note with 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
 */
@SuppressWarnings("unchecked")
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 File: DLockGenerator.java    From dlock with 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
Source File: SimpleMessageListenerContainer.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * 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;
}