Java Code Examples for org.springframework.util.StringUtils.isEmpty()

The following are Jave code examples for showing how to use isEmpty() of the org.springframework.util.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: apollo-custom   File: FavoriteService.java   View Source Code Vote up 6 votes
public List<Favorite> search(String userId, String appId, Pageable page) {
  boolean isUserIdEmpty = StringUtils.isEmpty(userId);
  boolean isAppIdEmpty = StringUtils.isEmpty(appId);

  if (isAppIdEmpty && isUserIdEmpty) {
    throw new BadRequestException("user id and app id can't be empty at the same time");
  }

  //search by userId
  if (isAppIdEmpty && !isUserIdEmpty) {
    return favoriteRepository.findByUserIdOrderByPositionAscDataChangeCreatedTimeAsc(userId, page);
  }

  //search by appId
  if (!isAppIdEmpty && isUserIdEmpty) {
    return favoriteRepository.findByAppIdOrderByPositionAscDataChangeCreatedTimeAsc(appId, page);
  }

  //search by userId and appId
  return Arrays.asList(favoriteRepository.findByUserIdAndAppId(userId, appId));
}
 
Example 2
Project: spring-backend-boilerplate   File: HmacUtils.java   View Source Code Vote up 6 votes
public static byte[] encode(String secret, String data) throws Exception {
	if (StringUtils.isEmpty(secret) || StringUtils.isEmpty(data)) {
		throw new IllegalArgumentException("Secret and Data must be supplied.");
	}

	Mac mac = Mac.getInstance("HmacSHA256");
	// get the bytes of the hmac key and data string
	// byte[] secretByte = secret.getBytes();
	byte[] secretByte = new Hex().decode(secret.getBytes());
	// byte[] secretByte = hexStringToByteArray(secret);
	byte[] dataBytes = data.getBytes("UTF-8");
	SecretKey secretKey = new SecretKeySpec(secretByte, "HmacSHA256");

	mac.init(secretKey);
	byte[] doFinal = mac.doFinal(dataBytes);
	return doFinal;
	// byte[] hexB = new Hex().encode(doFinal);
	// return hexB;
}
 
Example 3
Project: springboot_cwenao   File: HbaseFindBuilder.java   View Source Code Vote up 6 votes
/**
 * by map
 * @param map
 * @return
 */
public HbaseFindBuilder build(Map<String,String> map) {

    if (map == null || map.size() <= 0) {
        return this;
    }

    PropertyDescriptor p = null;
    byte[] qualifierByte = null;

    for (String value : map.values()) {
        if (StringUtils.isEmpty(value)) {
            continue;
        }

        p = fieldsMap.get(value.trim());
        qualifierByte = result.getValue(family.getBytes(), HumpNameOrMethodUtils.humpEntityForVar(value).getBytes());

        if (qualifierByte != null && qualifierByte.length > 0) {
            beanWrapper.setPropertyValue(p.getName(), Bytes.toString(qualifierByte));
            propertiesSet.add(p.getName());
        }
    }

    return this;
}
 
Example 4
Project: incubator-servicecomb-java-chassis   File: RemoteHostElement.java   View Source Code Vote up 6 votes
@Override
public String getFormattedElement(AccessLogParam accessLogParam) {
  HttpServerRequest request = accessLogParam.getRoutingContext().request();
  if (null == request) {
    return EMPTY_RESULT;
  }

  SocketAddress remoteAddress = request.remoteAddress();
  if (null == remoteAddress) {
    return EMPTY_RESULT;
  }

  String remoteHost = remoteAddress.host();
  if (StringUtils.isEmpty(remoteHost)) {
    return EMPTY_RESULT;
  }
  return remoteHost;
}
 
Example 5
Project: admin-shiro   File: RoleDO.java   View Source Code Vote up 5 votes
public String getSort() {
    if(StringUtils.isEmpty(sort)){
        return "createdAt";
    }else{
        return sort;
    }
}
 
Example 6
Project: spring-jdbc-orm   File: PageParams.java   View Source Code Vote up 5 votes
public String getOrder() {
    //默诵为顺序
    if (StringUtils.isEmpty(order)) {
        return "ASC";
    }
    return order;
}
 
Example 7
Project: SkillWill   File: UserService.java   View Source Code Vote up 5 votes
private List<User> filterByLocation(List<User> unfiltered, String location) {
  if (StringUtils.isEmpty(location)) {
    return unfiltered;
  }
  return unfiltered.stream()
      .filter(user -> user.getLdapDetails().getLocation().equals(location))
      .collect(Collectors.toList());
}
 
Example 8
Project: amanda   File: PhysicalNamingStrategyImpl.java   View Source Code Vote up 5 votes
private Identifier convert(Identifier identifier) {
    if (identifier == null || StringUtils.isEmpty(identifier.getText())) {
        return identifier;
    }

    String newName = addUnderscores(identifier.getText());
    return Identifier.toIdentifier(newName);
}
 
Example 9
Project: spring-backend-boilerplate   File: HmacUtils.java   View Source Code Vote up 5 votes
public static byte[] encode(byte[] secret, String data) throws Exception {
	if (secret == null || StringUtils.isEmpty(data)) {
		throw new IllegalArgumentException("Secret and Data must be supplied.");
	}

	Mac mac = Mac.getInstance("HmacSHA256");
	byte[] dataBytes = data.getBytes("UTF-8");
	SecretKey secretKey = new SecretKeySpec(secret, "HmacSHA256");

	mac.init(secretKey);
	byte[] doFinal = mac.doFinal(dataBytes);
	return doFinal;
}
 
Example 10
Project: spring-cloud-vault-connector   File: VaultConnectorBootstrapConfiguration.java   View Source Code Vote up 5 votes
@Bean
public VaultConnectorConfigurer cloudVaultConfigurer() {

	List<String> activeProfiles = Arrays.asList(environment.getActiveProfiles());

	List<SecretBackendMetadata> backends = new ArrayList<SecretBackendMetadata>();

	List<String> order = connectorVaultProperties.getBackends();

	if (order.size() == 1
			&& order.contains(VaultConnectorGenericBackendProperties.DEFAULT)) {
		order = getDefaultOrder(vaultServiceInfo);
	}

	for (String cloudBackend : order) {

		String backend = getBackend(cloudBackend, vaultServiceInfo);

		List<String> contexts = GenericSecretBackendMetadata.buildContexts(
				genericBackendProperties, activeProfiles);

		if (StringUtils.isEmpty(backend)) {
			throw new IllegalArgumentException(String.format(
					"Cannot resolve backend for %s", cloudBackend));
		}

		for (String context : contexts) {
			backends.add(GenericSecretBackendMetadata.create(backend, context));
		}
	}

	return new VaultConnectorConfigurer(backends);
}
 
Example 11
Project: FastBootWeixin   File: WxUrlUtils.java   View Source Code Vote up 5 votes
public static String mediaUrl(String requestUrl, String targetUrl) {
    String lowerUrl = targetUrl.toLowerCase();
    if (lowerUrl.startsWith(HTTP_PROTOCOL) || lowerUrl.startsWith(HTTPS_PROTOCOL)) {
        return targetUrl;
    }
    if (lowerUrl.startsWith(BASE_PATH) && !StringUtils.isEmpty(requestUrl)) {
        URI uri = URI.create(requestUrl);
        String hostUrl = uri.getScheme() + "://" + uri.getHost();
        return hostUrl + targetUrl;
    } else {
        return HTTP_PROTOCOL + targetUrl;
    }
}
 
Example 12
Project: iot-edge-greengrass   File: BasicJsonConverter.java   View Source Code Vote up 5 votes
protected DeviceData parseDeviceData(DocumentContext document) throws ParseException {
    long ts = System.currentTimeMillis();
    String deviceName = eval(document, deviceNameJsonExpression);
    String deviceType = null;
    if (!StringUtils.isEmpty(deviceTypeJsonExpression)) {
        deviceType = eval(document, deviceTypeJsonExpression);
    }
    if (!StringUtils.isEmpty(deviceName)) {
        List<KvEntry> attrData = getKvEntries(document, attributes);
        List<TsKvEntry> tsData = getTsKvEntries(document, timeseries, ts);
        return new DeviceData(deviceName, deviceType, attrData, tsData);
    } else {
        return null;
    }
}
 
Example 13
Project: Persephone   File: Application.java   View Source Code Vote up 5 votes
public boolean isAuthValid() {
	if(AuthScheme.BASIC == authScheme) {
		return !StringUtils.isEmpty(actuatorUsername) && !StringUtils.isEmpty(actuatorPassword);
	}

	return true;
}
 
Example 14
Project: incubator-servicecomb-java-chassis   File: SwaggerGenerator.java   View Source Code Vote up 5 votes
/**
 * 查找必填但是没值的字段,将之设置为默认值
 * 如果无法构造默认值,则抛出异常
 */
protected void correctSwagger() {
  if (StringUtils.isEmpty(swagger.getSwagger())) {
    swagger.setSwagger("2.0");
  }

  correctBasePath();
  correctInfo();
  correctProduces();
  correctConsumes();
}
 
Example 15
Project: DingTalkRobot-SpringBoot   File: ListenerUtils.java   View Source Code Vote up 5 votes
static String getServerName(String argName) {
    if (StringUtils.isEmpty(argName)) {
        return "服务器";
    } else {
        return argName + " ";
    }
}
 
Example 16
Project: spring-backend-boilerplate   File: NewsRepositoryImpl.java   View Source Code Vote up 5 votes
private Query buildQuery(NewsQueryRequest request) {
	QueryBuilder queryBuilder = new QueryBuilder();
	if (!StringUtils.isEmpty(request.getTitle())) {
		queryBuilder.add(Criteria.where("title").regex(request.getTitle()));
	}
	if (!StringUtils.isEmpty(request.getCategory())) {
		queryBuilder.add(Criteria.where("category").regex(request.getCategory()));
	}

	if (request.getPublished() != null) {
		queryBuilder.add(Criteria.where("published").is(request.getPublished().booleanValue()));
	}

	if (request.getNewsType() != null) {
		queryBuilder.add(Criteria.where("newsType").is(request.getNewsType()));
	}

	if (request.getCreatedAtBegin() != null && request.getCreatedAtEnd() != null) {
		queryBuilder.and(Criteria.where("createdAt").gte(request.getCreatedAtBegin()))
				    .and(Criteria.where("createdAt").lte(request.getCreatedAtEnd()));
	} else if (request.getCreatedAtBegin() != null) {
		queryBuilder.add(Criteria.where("createdAt").gte(request.getCreatedAtBegin()));
	} else if (request.getCreatedAtEnd() != null) {
		queryBuilder.add(Criteria.where("createdAt").lte(request.getCreatedAtEnd()));
	}

	if (request.getBeginDate() != null && request.getEndDate() != null) {
		queryBuilder.and(Criteria.where("publishedAt").gte(request.getBeginDate()))
					.and(Criteria.where("publishedAt").lte(request.getEndDate()));
	} else if (request.getBeginDate() != null) {
		queryBuilder.add(Criteria.where("publishedAt").gte(request.getBeginDate()));
	} else if (request.getEndDate() != null) {
		queryBuilder.add(Criteria.where("publishedAt").lte(request.getEndDate()));
	}
	return queryBuilder.build();
}
 
Example 17
Project: hibatis   File: Message.java   View Source Code Vote up 4 votes
public String getKey() {
	return StringUtils.isEmpty(key) ? "" : key;
}
 
Example 18
Project: sctalk   File: LoginServiceController.java   View Source Code Vote up 4 votes
/**
 * 登录
 * @param param 用户名或手机号phone
 * @return 登录成功后返回用户基本信息
 * @since  1.0
 */
@PostMapping(path = "/login")
public BaseModel<UserEntity> login(@RequestBody LoginReq param) {

    BaseModel<UserEntity> userRes = new BaseModel<>();
    String key = RedisKeys.concat(RedisKeys.USER_LOGIN_FAILD, param.getName());
    ValueOperations<String, String> faildCountOps = redisTemplate.opsForValue();
    String faildCount = faildCountOps.get(key);
    int faild = 0;
    if (!StringUtils.isEmpty(faildCount)) {
        faild = Integer.parseInt(faildCount);
    }
    if (faild > 5) {
        return userRes.setResult(LoginCmdResult.LOGIN_PASSWORD_LOCK);
    }
    
    // 改为:用户名或手机号皆可登录
    SearchCriteria<IMUser> userSearchCriteria = new SearchCriteria<>();
    userSearchCriteria.add(JpaRestrictions.or(JpaRestrictions.eq("name", param.getName(), false),
            JpaRestrictions.eq("phone", param.getName(), false)));
    userSearchCriteria.add(JpaRestrictions.ne("status", DBConstant.USER_STATUS_LEAVE, false));
    List<IMUser> users = userRepository.findAll(userSearchCriteria);
    
    if (users.isEmpty()) {
        logger.debug("用户{}登录失败", param.getName());
        return userRes.setResult(LoginCmdResult.LOGIN_NOUSER);
    }

    IMUser user = users.get(0);

    if (passwordEncoder.matches(param.getPassword(), user.getPassword())) {
        // 密码正确
        UserEntity userEntity = new UserEntity();
        userEntity.setId(user.getId());
        userEntity.setMainName(user.getNick());
        userEntity.setAvatar(user.getAvatar());
        userEntity.setCreated(user.getCreated());
        userEntity.setDepartmentId(user.getDepartId());
        userEntity.setPeerId(user.getId());
        userEntity.setPhone(user.getPhone());
        userEntity.setRealName(user.getName());
        userEntity.setStatus(user.getStatus());
        userEntity.setGender(user.getSex());
        userEntity.setUpdated(user.getUpdated());
        userEntity.setEmail(user.getEmail());
        userEntity.setPinyinName(user.getDomain());
        userEntity.setSignInfo(user.getSignInfo());
        userRes.setData(userEntity);

        // 如果登陆成功,则清除错误尝试限制
        if (faild > 0) {
            redisTemplate.delete(key);
        }
    } else {

        // 密码错误,记录一次登陆失败
        faildCountOps.set(key, String.valueOf(++faild), 30, TimeUnit.MINUTES);
        return userRes.setResult(LoginCmdResult.LOGIN_NOUSER);
    }
    return userRes;
}
 
Example 19
Project: akka-persistance-ignite   File: IgniteConfigProvider.java   View Source Code Vote up 4 votes
/**
 * @param actorSystem akka actor system
 * @return return the configured ignite properties for the plugin
 */
@Override
public IgniteProperties apply(ActorSystem actorSystem) {

    final Config config = actorSystem.settings().config();

    if (config.getInt( PropertiesNames.ASYNC_THREADS.getPropertyName()) != 0) {
        igniteProperties.setAsyncCallbackPoolSize(config
                .getInt( PropertiesNames.ASYNC_THREADS.getPropertyName()));
    }
    if (config.getInt( PropertiesNames.DATA_STREAMER_THREADS.getPropertyName()) != 0) {
        igniteProperties.setDataStreamerThreadPoolSize(config
                .getInt( PropertiesNames.DATA_STREAMER_THREADS.getPropertyName()));
    }
    if (config.getInt( PropertiesNames.MANAGEMENT_THREADS.getPropertyName()) != 0) {
        igniteProperties.setManagementThreadPoolSize(config
                .getInt( PropertiesNames.MANAGEMENT_THREADS.getPropertyName()));
    }
    if (config.getInt( PropertiesNames.PUBLIC_THREADS.getPropertyName()) != 0) {
        igniteProperties.setPublicThreadPoolSize(config
                .getInt( PropertiesNames.PUBLIC_THREADS.getPropertyName()));
    }
    if (config.getInt( PropertiesNames.SYSTEM_THREADS.getPropertyName()) != 0) {
        igniteProperties.setSystemThreadPoolSize(config
                .getInt( PropertiesNames.SYSTEM_THREADS.getPropertyName()));
    }
    if (config.getInt( PropertiesNames.QUERY_THREADS.getPropertyName()) != 0) {
        igniteProperties.setQueryThreadPoolSize(config
                .getInt( PropertiesNames.QUERY_THREADS.getPropertyName()));
    }
    if (config.getInt( PropertiesNames.REBALANCE_THREADS.getPropertyName()) != 0) {
        igniteProperties.setRebalanceThreadPoolSize(config
                .getInt( PropertiesNames.REBALANCE_THREADS.getPropertyName()));
    }
    if (config.getInt( PropertiesNames.METRICS_LOG_FREQUENCY.getPropertyName()) > 0) {
        igniteProperties.setMetricsLogFrequency(config
                .getInt( PropertiesNames.METRICS_LOG_FREQUENCY.getPropertyName()));
    }
    if (config.getInt( PropertiesNames.IGNITE_CONNECTOR_PORT.getPropertyName()) != 0) {
        igniteProperties.setIgniteConnectorPort(config
                .getInt( PropertiesNames.IGNITE_CONNECTOR_PORT.getPropertyName()));
    }
    if (!StringUtils.isEmpty(config.getString( PropertiesNames.IGNITE_PERSISTANCE_FILE_PATH.getPropertyName()))) {
        igniteProperties.setIgnitePersistenceFilePath(config
                .getString( PropertiesNames.IGNITE_PERSISTANCE_FILE_PATH.getPropertyName()));
    }
    if (!StringUtils.isEmpty(config.getString( PropertiesNames.IGNITE_SERVER_PORT_RANGE.getPropertyName()))) {
        igniteProperties.setIgniteServerPortRange(config
                .getString( PropertiesNames.IGNITE_SERVER_PORT_RANGE.getPropertyName()));
    }
    if (!StringUtils.isEmpty(config.getString( PropertiesNames.TCP_DISCOVERY_ADDRESSES.getPropertyName()))) {
        igniteProperties.setTcpDiscoveryAddresses(config
                .getString( PropertiesNames.TCP_DISCOVERY_ADDRESSES.getPropertyName()));
    }
    if (config.getBoolean( PropertiesNames.IS_CLIENT_NODE.getPropertyName())) {
        igniteProperties.setClientNode(config.getBoolean( PropertiesNames.IS_CLIENT_NODE.getPropertyName()));
    }
    if (config.getBoolean( PropertiesNames.ENABLE_FILE_PERSISTANCE.getPropertyName())) {
        igniteProperties.setEnableFilePersistence(config
                .getBoolean( PropertiesNames.ENABLE_FILE_PERSISTANCE.getPropertyName()));
    }
    if (config.getBoolean( PropertiesNames.PEER_CLASS_LOADING.getPropertyName())) {
        igniteProperties.setPeerClassLoadingEnabled(config
                .getBoolean( PropertiesNames.PEER_CLASS_LOADING.getPropertyName()));
    }
    return igniteProperties;
}
 
Example 20
Project: sctalk   File: JpaRestrictions.java   View Source Code Vote up 2 votes
/**
 * 模糊匹配
 * 
 * @param fieldName 字段名
 * @param value 字段值
 * @param ignoreNull 是否忽然空值
 * @return 条件表达式
 */
public static SimpleExpression rlike(String fieldName, String value, boolean ignoreNull) {
    if (StringUtils.isEmpty(value))
        return null;
    return new SimpleExpression(fieldName, value, Operator.RLIKE);
}