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

The following examples show how to use org.springframework.util.Assert#isNull() . 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: SignCreate.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
public Sign transformation(SignService signService, CoinService coinService) {
    //校验是否签到进行中
    Sign underway = signService.fetchUnderway();
    Assert.isNull(underway, "validate underway!");

    //校验币种存在
    Coin coin = coinService.findByUnit(unit);
    Assert.notNull(coin, "validate unit!");

    //校验时间
    DateUtil.validateEndDate(endDate);

    //返回对象
    Sign sign = new Sign();
    sign.setAmount(amount);
    sign.setCoin(coin);
    sign.setEndDate(endDate);

    return sign;
}
 
Example 2
Source File: AccountServiceImpl.java    From DAFramework with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public EAccount create(EUser user) {

	EAccount existing = findByName(user.getUsername());
	Assert.isNull(existing, "account already exists: " + user.getUsername());

	authClient.createUser(user);
	EAccount account = new EAccount();
	account.setFullName(user.getUsername());

	//accountMapper.insert(account);
	log.info("new account has been created: " + account.getFullName());

	return account;
}
 
Example 3
Source File: GeneralEntityService.java    From rebuild with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 为 {@link Record} 补充默认值
 *
 * @param recordOfNew
 */
protected void appendDefaultValue(Record recordOfNew) {
	Assert.isNull(recordOfNew.getPrimary(), "Must be new record");

	Entity entity = recordOfNew.getEntity();
	if (MetadataHelper.isBizzEntity(entity.getEntityCode()) || !MetadataHelper.hasPrivilegesField(entity)) {
		return;
	}

	for (Field field : entity.getFields()) {
		if (MetadataHelper.isCommonsField(field) || recordOfNew.hasValue(field.getName(), true)) {
			continue;
		}

		Object defVal = DefaultValueHelper.exprDefaultValue(field, (String) field.getDefaultValue());
		if (defVal != null) {
			recordOfNew.setObjectValue(field.getName(), defVal);
		}
	}
}
 
Example 4
Source File: LocalRegistrationsTest.java    From fiware-cepheus with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testUnregisterWithZeroDuration() throws Exception {
    RegisterContext registerContext = createRegistrationContext();
    String registrationId = localRegistrations.updateRegistrationContext(registerContext);

    // Remove registration using a zero duration
    RegisterContext zeroDuration = createRegistrationContext();
    zeroDuration.setRegistrationId(registrationId);
    zeroDuration.setDuration("PT0S");
    localRegistrations.updateRegistrationContext(zeroDuration);

    Assert.isNull(localRegistrations.getRegistration(registrationId));

    verify(remoteRegistrations).removeRegistration(registrationId);
    verify(registrationsRepository).removeRegistration(eq(registrationId));
}
 
Example 5
Source File: RegisterController.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * 发送绑定邮箱验证码
 *
 * @param email
 * @param user
 * @return
 */
@RequestMapping("/bind/email/code")
@ResponseBody
@Transactional(rollbackFor = Exception.class)
public MessageResult sendBindEmail(String email, @SessionAttribute(SESSION_MEMBER) AuthMember user) {
    Assert.isTrue(ValidateUtil.isEmail(email), localeMessageSourceService.getMessage("WRONG_EMAIL"));
    Member member = memberService.findOne(user.getId());
    Assert.isNull(member.getEmail(), localeMessageSourceService.getMessage("BIND_EMAIL_REPEAT"));
    Assert.isTrue(!memberService.emailIsExist(email), localeMessageSourceService.getMessage("EMAIL_ALREADY_BOUND"));
    String code = String.valueOf(GeneratorUtil.getRandomNumber(100000, 999999));
    ValueOperations valueOperations = redisTemplate.opsForValue();
    if (valueOperations.get(EMAIL_BIND_CODE_PREFIX + email) != null) {
        return error(localeMessageSourceService.getMessage("EMAIL_ALREADY_SEND"));
    }
    try {
        sentEmailCode(valueOperations, email, code);
    } catch (Exception e) {
        e.printStackTrace();
        return error(localeMessageSourceService.getMessage("SEND_FAILED"));
    }
    return success(localeMessageSourceService.getMessage("SENT_SUCCESS_TEN"));
}
 
Example 6
Source File: Permission.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
/**
 * Set the ID of a user that will be assigned permissions on a credential. This is
 * typically a GUID generated by UAA when a user account is created.
 * @param zoneId zone ID; must not be {@literal null}
 * @param userId user ID; must not be {@literal null}
 * @return the builder
 */
public CredentialPermissionBuilder user(String zoneId, String userId) {
	Assert.notNull(zoneId, "zoneId must not be null");
	Assert.notNull(userId, "userId must not be null");
	Assert.isNull(this.actor, "only one actor can be specified");
	this.actor = Actor.user(zoneId, userId);
	return this;
}
 
Example 7
Source File: SimpleParallelFetchTest.java    From multi-task with Apache License 2.0 5 votes vote down vote up
/**
 * 模拟网络异常超时测试
 */
@Test(expected = TaskTimeoutException.class)
public void testParallelFetchWithTimeOutException() {
    QueryParam qp = new QueryParam();

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

    List<DeviceViewItem> out = ctx.getResult("doSthVerySlowFetcher");
    Assert.isNull(out);
}
 
Example 8
Source File: MessageBundleTest.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testRevert(){
    List<MessageBundleProperty> list = messageBundleService.getAllProperties(localeEn.toString(), null, moduleName);
    MessageBundleProperty prop = list.get(0);
    prop.setValue("newvalue");
    messageBundleService.updateMessageBundleProperty(prop);
    messageBundleService.revert(prop);

    MessageBundleProperty loadedProp = messageBundleService.getMessageBundleProperty(prop.getId());
    Assert.isNull(loadedProp.getValue());
}
 
Example 9
Source File: CourseUnitaryTest.java    From full-teaching with Apache License 2.0 5 votes vote down vote up
@Test
public void newCourseTest() {
	Course c2 = new Course();
	Assert.notNull(c2);
	
	Course c = new Course(title, image, teacher);
	Assert.notNull(c);
	Assert.isTrue(c.getTeacher().equals(teacher));
	Assert.isTrue(c.getImage().equals(image));
	Assert.isTrue(c.getTitle().equals(title));
	Assert.notNull(c.getSessions());
	Assert.notNull(c.getAttenders());
	Assert.isNull(c.getCourseDetails());
	
	CourseDetails cd = new CourseDetails();
	
	Course c3 = new Course(title, image, teacher, cd);
	Assert.notNull(c3);
	Assert.isTrue(c3.getTeacher().equals(teacher));
	Assert.isTrue(c3.getImage().equals(image));
	Assert.isTrue(c3.getTitle().equals(title));
	Assert.notNull(c3.getSessions());
	Assert.notNull(c3.getAttenders());
	Assert.notNull(c3.getCourseDetails());
	
	Assert.isTrue(c3.getCourseDetails().equals(cd));
}
 
Example 10
Source File: SmsController.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 绑定手机号验证码
 *
 * @param phone
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/bind/code", method = RequestMethod.POST)
public MessageResult setBindPhoneCode(String country, String phone, @SessionAttribute(SESSION_MEMBER) AuthMember user) throws Exception {
    Member member = memberService.findOne(user.getId());
    Assert.isNull(member.getMobilePhone(), localeMessageSourceService.getMessage("REPEAT_PHONE_REQUEST"));
    MessageResult result;
    String randomCode = String.valueOf(GeneratorUtil.getRandomNumber(100000, 999999));

    // 修改所在国家
    if (StringUtils.isNotBlank(country)) {
        Country one = countryService.findOne(country);
        if (one != null) {
            member.setCountry(one);
            memberService.saveAndFlush(member);
        }
    }


    if ("86".equals(member.getCountry().getAreaCode())) {
        if (!ValidateUtil.isMobilePhone(phone.trim())) {
            return error(localeMessageSourceService.getMessage("PHONE_EMPTY_OR_INCORRECT"));
        }
        result = smsProvider.sendVerifyMessage(phone, randomCode);
    } else {
        result = smsProvider.sendInternationalMessage(randomCode, member.getCountry().getAreaCode() + phone);
    }
    if (result.getCode() == 0) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String key = SysConstant.PHONE_BIND_CODE_PREFIX + phone;
        valueOperations.getOperations().delete(key);
        // 缓存验证码
        valueOperations.set(key, randomCode, 10, TimeUnit.MINUTES);
        return success(localeMessageSourceService.getMessage("SEND_SMS_SUCCESS"));
    } else {
        return error(localeMessageSourceService.getMessage("SEND_SMS_FAILED"));
    }
}
 
Example 11
Source File: AccountService.java    From microservice-app with GNU General Public License v3.0 5 votes vote down vote up
@Transactional
public AccountDto update(String id, AccountDto accountDto) {
    Assert.isNull(id, "Id cannot be null");
    Optional<Account> account = accountRepository.findById(id);
    Account accountToUpdate = account.map(it -> {
        it.setBirthDate(accountDto.getBirthDate());
        it.setName(accountDto.getName());
        it.setSurname(accountDto.getSurname());
        return it;
    }).orElseThrow(IllegalArgumentException::new);
    return modelMapper.map(accountRepository.save(accountToUpdate), AccountDto.class);
}
 
Example 12
Source File: Permission.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
/**
 * Set the ID of a user that will be assigned permissions on a credential. This is
 * typically a GUID generated by UAA when a user account is created.
 * @param userId user ID; must not be {@literal null}
 * @return the builder
 */
public CredentialPermissionBuilder user(String userId) {
	Assert.notNull(userId, "userId must not be null");
	Assert.isNull(this.actor, "only one actor can be specified");
	this.actor = Actor.user(userId);
	return this;
}
 
Example 13
Source File: NodeRegistrationImpl.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
private void subscribe() {
    DockerEventsConfig cfg = nodeStorage.getDockerEventConfig();
    final int periodInSeconds = cfg.getPeriodInSeconds();
    log.info("Register log fetcher from {} node, repeat every {} seconds", name, periodInSeconds);
    Assert.isNull(this.logFuture, "Future of docker logging is not null");
    this.logFuture = logFetcher.scheduleAtFixedRate(() -> {
        // we must handle errors here, because its may stop of task scheduling
        // for example - temporary disconnect of node will breaks logs fetching due to system restart
          try {
              Long time = System.currentTimeMillis();
              Long afterTime = time + periodInSeconds * 1000L;
              GetEventsArg getEventsArg = GetEventsArg.builder()
                .since(time)
                .until(afterTime)
                .watcher(this::proxyDockerEvent)
                .build();
              log.debug("getting events args {}", getEventsArg);
              try (TempAuth ta = TempAuth.asSystem()) {
                  docker.subscribeToEvents(getEventsArg);
              }
          } catch (Exception e) {
              log.error("Can not fetch logs from {}, try again after {} seconds, error: {}", name, periodInSeconds, e.toString());
          }
      },
      cfg.getInitialDelayInSeconds(),
      periodInSeconds, TimeUnit.SECONDS);
}
 
Example 14
Source File: CosmosAnnotationUnitTest.java    From spring-data-cosmosdb with MIT License 5 votes vote down vote up
@Test
public void testDefaultIndexingPolicyAnnotation() {
    final IndexingPolicy policy = personInfo.getIndexingPolicy();
    final Document documentAnnotation = NoDBAnnotationPerson.class.getAnnotation(Document.class);
    final DocumentIndexingPolicy policyAnnotation =
            NoDBAnnotationPerson.class.getAnnotation(DocumentIndexingPolicy.class);

    Assert.isNull(documentAnnotation, "NoDBAnnotationPerson class should not have Document annotation");
    Assert.isNull(policyAnnotation, "NoDBAnnotationPerson class should not have DocumentIndexingPolicy annotation");
    Assert.notNull(policy, "NoDBAnnotationPerson class collection policy should not be null");

    // ContainerName, RequestUnit, Automatic and IndexingMode
    Assert.isTrue(personInfo.getContainerName().equals(NoDBAnnotationPerson.class.getSimpleName()),
            "should be default collection name");
    Assert.isTrue(personInfo.getRequestUnit() == TestConstants.DEFAULT_REQUEST_UNIT,
            "should be default request unit");
    Assert.isTrue(policy.automatic() == TestConstants.DEFAULT_INDEXINGPOLICY_AUTOMATIC,
            "should be default indexing policy automatic");
    Assert.isTrue(policy.indexingMode() == TestConstants.DEFAULT_INDEXINGPOLICY_MODE,
            "should be default indexing policy mode");

    // IncludedPaths and ExcludedPaths
    // We do not use testIndexingPolicyPathsEquals generic here, for unit test do not create cosmosdb instance,
    // and the paths of policy will never be set from azure service.
    // testIndexingPolicyPathsEquals(policy.getIncludedPaths(), TestConstants.DEFAULT_INCLUDEDPATHS);
    // testIndexingPolicyPathsEquals(policy.getExcludedPaths(), TestConstants.DEFAULT_EXCLUDEDPATHS);
    Assert.isTrue(policy.includedPaths().isEmpty(), "default includedpaths size must be 0");
    Assert.isTrue(policy.excludedPaths().isEmpty(), "default excludedpaths size must be 0");
}
 
Example 15
Source File: SysUserDetailsService.java    From DAFramework with MIT License 5 votes vote down vote up
/**
 * 创建用户
 *
 * @param user
 * @return
 */
public EUser create(EUser user) {
	EUser existing = userDao.fetchByName(user.getUsername());
	Assert.isNull(existing, "user already exists: " + user.getUsername());

	user.setPassword(passwordEncoder.encode(user.getPassword()));
	user.setRoles(roleDao.getDefaultRoles());
	EUser newUser = userDao._insert(user);
	// ccount.setUser(newUser);
	userDao._insertRelation(user, "roles");
	// accountDao._insertLinks(account,"user");
	log.info("new user has been created: {}-{}", user.getUsername(), newUser.getId());
	return newUser;
}
 
Example 16
Source File: BusinessObjectFormatServiceImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@NamespacePermission(fields = "#businessObjectFormatKey.namespace", permissions = NamespacePermissionEnum.WRITE)
@Override
public BusinessObjectFormat updateBusinessObjectFormatRetentionInformation(BusinessObjectFormatKey businessObjectFormatKey,
    BusinessObjectFormatRetentionInformationUpdateRequest updateRequest)
{
    // Validate and trim the business object format retention information update request update request.
    Assert.notNull(updateRequest, "A business object format retention information update request must be specified.");
    Assert.notNull(updateRequest.isRecordFlag(), "A record flag in business object format retention information update request must be specified.");
    businessObjectFormatHelper.validateBusinessObjectFormatKey(businessObjectFormatKey, false);
    Assert.isNull(businessObjectFormatKey.getBusinessObjectFormatVersion(), "Business object format version must not be specified.");

    // Validate business object format retention information.
    RetentionTypeEntity recordRetentionTypeEntity = null;
    if (updateRequest.getRetentionType() != null)
    {
        // Trim the business object format retention in update request.
        updateRequest.setRetentionType(updateRequest.getRetentionType().trim());

        // Retrieve and ensure that a retention type exists.
        recordRetentionTypeEntity = businessObjectFormatDaoHelper.getRecordRetentionTypeEntity(updateRequest.getRetentionType());

        if (recordRetentionTypeEntity.getCode().equals(RetentionTypeEntity.PARTITION_VALUE))
        {
            Assert.notNull(updateRequest.getRetentionPeriodInDays(),
                String.format("A retention period in days must be specified for %s retention type.", RetentionTypeEntity.PARTITION_VALUE));
            Assert.isTrue(updateRequest.getRetentionPeriodInDays() > 0,
                String.format("A positive retention period in days must be specified for %s retention type.", RetentionTypeEntity.PARTITION_VALUE));
        }
        else
        {
            Assert.isNull(updateRequest.getRetentionPeriodInDays(),
                String.format("A retention period in days cannot be specified for %s retention type.", recordRetentionTypeEntity.getCode()));
        }
    }
    else
    {
        // Do not allow retention period to be specified without retention type.
        Assert.isNull(updateRequest.getRetentionPeriodInDays(), "A retention period in days cannot be specified without retention type.");
    }

    // Retrieve and ensure that a business object format exists.
    BusinessObjectFormatEntity businessObjectFormatEntity = businessObjectFormatDaoHelper.getBusinessObjectFormatEntity(businessObjectFormatKey);
    businessObjectFormatEntity.setRecordFlag(BooleanUtils.isTrue(updateRequest.isRecordFlag()));
    businessObjectFormatEntity.setRetentionPeriodInDays(updateRequest.getRetentionPeriodInDays());
    businessObjectFormatEntity.setRetentionType(recordRetentionTypeEntity);

    // Persist and refresh the entity.
    businessObjectFormatEntity = businessObjectFormatDao.saveAndRefresh(businessObjectFormatEntity);

    // Create and return the business object format object from the persisted entity.
    return businessObjectFormatHelper.createBusinessObjectFormatFromEntity(businessObjectFormatEntity);
}
 
Example 17
Source File: ScopeBeans.java    From haven-platform with Apache License 2.0 4 votes vote down vote up
void putBean(String name, Object bean) {
    synchronized (this.beans) {
        Object old = this.beans.putIfAbsent(name, bean);
        Assert.isNull(old, "Can not rewrite bean: old=" + old + " new=" + bean + "  name=" + name);
    }
}
 
Example 18
Source File: Attribute.java    From celerio with Apache License 2.0 4 votes vote down vote up
public void setColumnConfig(ColumnConfig columnConfig) {
    Assert.isNull(this.columnConfig, "you can set the columnConfig only once");
    this.columnConfig = columnConfig;
}
 
Example 19
Source File: DictServiceImpl.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
private void checkRepeat(Dict dict) {
	Dict dict1 = dictDao.selectByPrimaryKey(dict.getKey());
	Assert.isNull(dict1, "dict key is repeat");
}
 
Example 20
Source File: AppStatus.java    From spring-cloud-deployer with Apache License 2.0 2 votes vote down vote up
/**
 * Add an instance of {@code AppInstanceStatus} to build the status for
 * the app. This will be invoked once per individual app instance.
 *
 * @param instance status of individual app deployment
 * @return this {@code Builder}
 */
public Builder with(AppInstanceStatus instance) {
	Assert.isNull(generalState, "Can't build an AppStatus from app instances if generalState has been set");
	statuses.add(instance);
	return this;
}