下面列出了org.apache.commons.lang3.StringUtils#isAnyBlank ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@RequestMapping(value = "add", method = RequestMethod.POST)
public ResponseEntity<WrapperResponseEntity> addUser(@RequestBody UserEntity param){
SecurityUtil.requireSuperAdmin();
if(StringUtils.isAnyBlank(param.getName(),param.getMobile())){
throw new JeesuiteBaseException(1001, "用户名/手机号不能为空");
}
if(userMapper.findByName(param.getName()) != null){
throw new JeesuiteBaseException(1001, "用户名已存在");
}
if(userMapper.findByMobile(param.getMobile()) != null){
throw new JeesuiteBaseException(1001, "手机号已存在");
}
param.setPassword(UserEntity.encryptPassword(param.getMobile().substring(3)));
param.setStatus((short)1);
param.setType((short)2);
param.setCreatedAt(new Date());
userMapper.insertSelective(param);
return new ResponseEntity<WrapperResponseEntity>(new WrapperResponseEntity(param),HttpStatus.OK);
}
@RequestMapping(value = "perm/batch_create", method = RequestMethod.POST)
public @ResponseBody WrapperResponse<String> batchCreatePermResources(HttpServletRequest request,@RequestBody BatchCreateResourceParam param){
String[] menuNames = StringUtils.splitByWholeSeparator(param.getMenuName(), ">");
if(param.getApis() == null)throw new JeesuiteBaseException(400,"请填写关联接口");
for (int i = 0; i < param.getApis().size(); i++) {
ApiDefine apiDefine = param.getApis().get(i);
if(StringUtils.isAnyBlank(apiDefine.getMethod(),apiDefine.getName(),apiDefine.getUri())){
param.getApis().remove(i);
i--;
}
}
if(param.getApis().isEmpty())throw new JeesuiteBaseException(400,"请完整填写关联接口");
permissionService.batchCreatePermResources(param.getPlatformType(), menuNames, param.getMenuUri(), param.getApis());
boolean jsonSubmit = Boolean.parseBoolean(request.getParameter("jsonSubmit"));
return new WrapperResponse<>(jsonSubmit == false ? JsonUtils.toPrettyJson(param) : null);
}
public boolean addBlog(AddBlogParam param) {
try {
if (param == null
|| StringUtils.isAnyBlank(param.getTitle(), param.getRealContent(), param.getShowContent())) {
return false;
}
BlogPo po = new BlogPo();
BeanUtils.copyProperties(param, po);
blogDao.addBlog(po);
//插入新博客后,删除博客介绍缓存,强制下次查询走库
redisClient.delete(RedisKey.ALL_BLOG_DESC);
return true;
} catch (Exception e) {
log.error("add blogPo error, param:{}", JSON.toJSONString(param), e);
return false;
}
}
public SecurityConfig findOneByStack(Stack stack) {
SecurityConfig securityConfig = securityConfigRepository.findOneByStackId(stack.getId());
if (securityConfig != null && securityConfig.getSaltSecurityConfig() != null) {
SaltSecurityConfig saltSecurityConfig = securityConfig.getSaltSecurityConfig();
if (StringUtils.isAnyBlank(saltSecurityConfig.getSaltBootPasswordVault(), saltSecurityConfig.getSaltBootSignPrivateKeyVault(),
saltSecurityConfig.getSaltPasswordVault(), saltSecurityConfig.getSaltSignPrivateKeyVault())) {
LOGGER.debug("Migrate SaltSecurityConfig with id [{}] to vault", saltSecurityConfig.getId());
if (!saltSecurityConfig.getSaltBootPassword().equals(saltSecurityConfig.getSaltBootPasswordVault())) {
saltSecurityConfig.setSaltBootPasswordVault(saltSecurityConfig.getSaltBootPassword());
}
if (!saltSecurityConfig.getSaltBootSignPrivateKey().equals(saltSecurityConfig.getSaltBootSignPrivateKeyVault())) {
saltSecurityConfig.setSaltBootSignPrivateKeyVault(saltSecurityConfig.getSaltBootSignPrivateKey());
}
if (!saltSecurityConfig.getSaltSignPrivateKey().equals(saltSecurityConfig.getSaltPasswordVault())) {
saltSecurityConfig.setSaltPasswordVault(saltSecurityConfig.getSaltPassword());
}
if (!saltSecurityConfig.getSaltSignPrivateKey().equals(saltSecurityConfig.getSaltSignPrivateKeyVault())) {
saltSecurityConfig.setSaltSignPrivateKeyVault(saltSecurityConfig.getSaltSignPrivateKey());
}
saltSecurityConfig = disabledSaltSecurityConfigRepository.save(saltSecurityConfig);
securityConfig.setSaltSecurityConfig(saltSecurityConfig);
}
}
return securityConfig;
}
@Override
public void deleteFile(String storePath) {
String accessKey = options.getValue(oss_key);
String secretKey = options.getValue(oss_secret);
String domain = options.getValue(oss_domain);
String bucket = options.getValue(oss_bucket);
if (StringUtils.isAnyBlank(accessKey, secretKey, domain, bucket)) {
throw new MtonsException("请先在后台设置阿里云配置信息");
}
String path = StringUtils.remove(storePath, domain.trim());
Zone z = Zone.autoZone();
Configuration configuration = new Configuration(z);
Auth auth = Auth.create(accessKey, secretKey);
BucketManager bucketManager = new BucketManager(auth, configuration);
try {
bucketManager.delete(bucket, path);
} catch (QiniuException e) {
Response r = e.response;
log.error(e.getMessage(), r.toString());
}
}
private UpYun builder() {
String bucket = options.getValue(oss_bucket);
String operator = options.getValue(oss_operator);
String password = options.getValue(oss_password);
if (StringUtils.isAnyBlank(bucket, operator, password)) {
throw new MtonsException("请先在后台设置又拍云配置信息");
}
UpYun yun = new UpYun(bucket, operator, password);
yun.setTimeout(60);
yun.setApiDomain(UpYun.ED_AUTO);
yun.setDebug(true);
return yun;
}
@Override
public Optional<Login> deleteLogin(Login login) throws IOException {
LOG.debug(String.format("Deleting login %s for user %s", login.getId(), login.getUserId()));
if(StringUtils.isAnyBlank(login.getUserId(), login.getId())) {
throw new IllegalArgumentException("User ID and Login ID are required to delete a login");
}
String url = buildCanvasUrl(String.format("users/%s/logins/%s", login.getUserId(), login.getId()), emptyMap());
Response response = canvasMessenger.deleteFromCanvas(oauthToken, url, emptyMap());
return responseParser.parseToObject(Login.class, response);
}
/**
* Ensure that a tool object is valid for creation. The API requires certain fields to be filled out.
* Throws an IllegalArgumentException if the conditions are not met.
* @param tool The external tool object we are trying to create
*/
private void ensureToolValidForCreation(ExternalTool tool) {
//check for the unconditionally required fields
if(StringUtils.isAnyBlank(tool.getName(), tool.getPrivacyLevel(), tool.getConsumerKey(), tool.getSharedSecret())) {
throw new IllegalArgumentException("External tool requires all of the following for creation: name, privacy level, consumer key, shared secret");
}
//check that there is either a URL or a domain. One or the other is required
if(StringUtils.isBlank(tool.getUrl()) && StringUtils.isBlank(tool.getDomain())) {
throw new IllegalArgumentException("External tool requires either a URL or domain for creation");
}
}
public boolean addCommonUser(UserPo userPo) {
try {
if (userPo == null || StringUtils.isAnyBlank(
userPo.getUserName(), userPo.getPassword(), userPo.getRoles())) {
return false;
}
userDao.addUser(userPo);
return true;
} catch (Exception e) {
log.error("db error when add user, userPo:{}", JSON.toJSONString(userPo), e);
return false;
}
}
public GenericKeyIdentifier(KeyType type, String algo, String serial) {
if (StringUtils.isAnyBlank(algo, serial)) {
throw new IllegalArgumentException("Algorithm and/or Serial cannot be blank");
}
this.type = Objects.requireNonNull(type);
this.algo = algo;
this.serial = serial;
}
@ApiOperation(value = "新增账号")
@RequestMapping(value = "add", method = RequestMethod.POST)
public @ResponseBody WrapperResponse<String> addAccount(@RequestBody AccountParam param) {
if(StringUtils.isAnyBlank(param.getMobile(),param.getEmail(),param.getUsername())){
throw new JeesuiteBaseException(4001, "用户名、手机、邮箱必填");
}
accountService.addAccount(LoginContext.getIntFormatUserId(), param);
return new WrapperResponse<>();
}
@Override
public User findUser(String username, String domain) {
if (StringUtils.isAnyBlank(username, domain)) {
return null;
} else {
Collection<? extends GrantedAuthority> authorities = new ArrayList<>();
User user = new User(username, domain,
passwordEncoder.encode("secret"), true,
true, true, true, authorities);
return user;
}
}
@Override
public void process(Mxisd m, _MatrixClient client, _MatrixRoom room, CommandLine cmdLine) {
if (cmdLine.getArgList().size() != 3) {
room.sendNotice(getUsage());
return;
}
String medium = cmdLine.getArgList().get(1);
String address = cmdLine.getArgList().get(2);
if (StringUtils.isAnyBlank(medium, address)) {
room.sendNotice(getUsage());
return;
}
room.sendNotice("Processing...");
Optional<SingleLookupReply> r = m.getIdentity().find(medium, address, true);
if (!r.isPresent()) {
room.sendNotice("No result");
return;
}
SingleLookupReply lookup = r.get();
StrBuilder b = new StrBuilder();
b.append("Result for 3PID lookup of ").append(medium).append(" ").appendln(address).appendNewLine();
b.append("Matrix ID: ").appendln(lookup.getMxid().getId());
b.appendln("Validity:")
.append(" Not Before: ").appendln(lookup.getNotBefore())
.append(" Not After: ").appendln(lookup.getNotAfter());
b.appendln("Signatures:");
lookup.getSignatures().forEach((host, signs) -> {
b.append(" ").append(host).appendln(":");
signs.forEach((key, sign) -> b.append(" ").append(key).append(" -> ").appendln("OK"));
});
room.sendNotice(b.toString());
}
@Override
public User findUser(String username, String domain) {
if (StringUtils.isAnyBlank(username, domain)) {
return null;
} else {
Collection<? extends GrantedAuthority> authorities = new ArrayList<>();
User user = new User(username, domain,
passwordEncoder.encode("secret"), true,
true, true, true, authorities);
return user;
}
}
private OSSClient builder() {
String endpoint = options.getValue(oss_endpoint);
String accessKeyId = options.getValue(oss_key);
String accessKeySecret = options.getValue(oss_secret);
if (StringUtils.isAnyBlank(endpoint, accessKeyId, accessKeySecret)) {
throw new MtonsException("请先在后台设置阿里云配置信息");
}
return new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
@JsonCreator
public Category(@JsonProperty("categories") String... categories) {
if (categories.length > 0 && StringUtils.isAnyBlank(categories)) {
throw new EPSCommonException("Categories should't be blank " + Arrays.toString(categories));
}
String[] lowerCaseCategories = categories;
if (categories.length > 0) {
lowerCaseCategories = new String[categories.length];
for (int i = 0; i < categories.length; i++) {
lowerCaseCategories[i] = categories[i].toLowerCase();
}
}
this.categories = ImmutableList.copyOf(lowerCaseCategories);
}
@PostMapping(value = "/importGroups", consumes = "multipart/form-data")
public String showImportGroups(@RequestParam(required=false) String groupUploadedText, Model model, HttpServletRequest req) {
log.debug("showImportGroups called with value {}", groupUploadedText);
// Variable definition
Locale userLocale = sakaiService.getCurrentUserLocale();
Map<String, List<String>> importedGroupMap = new HashMap<String, List<String>>();
String uploadedText = StringUtils.EMPTY;
String groupFileUploadedText = StringUtils.EMPTY;
//Check the uploaded file and contents.
FileItem uploadedFileItem = (FileItem) req.getAttribute("groupUploadFile");
if (uploadedFileItem.getSize() > 0) {
try (Scanner scanner = new Scanner(uploadedFileItem.getInputStream(), StandardCharsets.UTF_8.name())) {
groupFileUploadedText = scanner.useDelimiter("\\A").next();
} catch (Exception e) {
log.error("The file {} provided is not valid.", uploadedFileItem.getName());
}
}
// Check if both options are blank and return an error message
if (StringUtils.isAllBlank(groupUploadedText, groupFileUploadedText)) {
return returnImportError(model, "import.error.inputrequired", userLocale);
}
// Process the submitted texts, combine the uploaded and the file into one String
uploadedText = String.format("%s\r\n%s", groupUploadedText, groupFileUploadedText);
String[] lineArray = uploadedText.split(BULK_LINE_DELIMITER);
for (String line : lineArray) {
if (StringUtils.isBlank(line)) {
continue;
}
String[] lineContentArray = line.split(BULK_FIELD_DELIMITER);
//Each line must contain a groupTitle and a userEid
if (lineContentArray.length == 2) {
String groupTitle = StringUtils.trimToNull(lineContentArray[0]);
String userEid = StringUtils.trimToNull(lineContentArray[1]);
if (StringUtils.isAnyBlank(groupTitle, userEid)) {
// One of the items of the line is blank, redirect to the import form again displaying an error.
return returnImportError(model, "import.error.wrongformat", userLocale);
}
if (groupTitle.length() > 99) {
// One of the items of the line has more than 99 characters, redirect to the import form again displaying an error.
return returnImportError(model, "import.error.titlelength", userLocale);
}
if (importedGroupMap.get(groupTitle) != null) {
// If the map contains an entry for that group, add the user to the list
importedGroupMap.get(groupTitle).add(userEid);
} else {
// If the map does not contain an entry for that group, create a list and add the member to the list
List<String> newUserlist = new ArrayList<String>();
newUserlist.add(userEid);
importedGroupMap.put(groupTitle, newUserlist);
}
} else {
// One line does not contain two items, redirect to the import form again displaying an error.
return returnImportError(model, "import.error.wrongformat", userLocale);
}
}
//Redirect to the confirmation page once the map are correct
return showImportConfirmation(model, importedGroupMap);
}
/**
* <pre>
* 代理前台客户端中扩展的请求
* 1.界面请求后台一般使用http请求
* 2.使用tcp代理,代替http请求
* </pre>
*
* @param command
* @return
*/
public CommandResponse proxy(Command command) {
CommandResponse commandResponse = new CommandResponse().setAction(CommandConst.ACTION_RES);
ErrorCode2 errCode = ErrorCode2.ERROR;
try {
ApiPluginProxyProto.ApiPluginProxyRequest request = ApiPluginProxyProto.ApiPluginProxyRequest
.parseFrom(command.getParams());
String siteUserId = command.getSiteUserId();
String pluginId = request.getPluginId();
String requestApi = request.getApi();
String requestParams = request.getParams();
LogUtils.requestDebugLog(logger, command, request.toString());
Map<Integer, String> header = command.getHeader();
String siteSessionId = header.get(CoreProto.HeaderKey.CLIENT_SOCKET_SITE_SESSION_ID_VALUE);
String pluginRefere = header.get(CoreProto.HeaderKey.PLUGIN_CLIENT_REFERER_VALUE);
if (!StringUtils.isAnyBlank(siteUserId, pluginId, requestApi)) {
PluginBean bean = SitePluginDao.getInstance().getPluginProfile(Integer.valueOf(pluginId));
if (bean != null && bean.getApiUrl() != null) {
String pluginUrl = this.buildUrl(bean.getApiUrl(), requestApi, null);
logger.debug("action={} pluginId={} api={} url={} params={}", command.getAction(), pluginId,
requestApi, pluginUrl, requestParams);
PluginProto.ProxyPluginPackage.Builder packageBuilder = PluginProto.ProxyPluginPackage.newBuilder();
packageBuilder.putPluginHeader(PluginProto.PluginHeaderKey.CLIENT_SITE_USER_ID_VALUE, siteUserId);
packageBuilder.putPluginHeader(PluginProto.PluginHeaderKey.CLIENT_SITE_SESSION_ID_VALUE,
siteSessionId);
packageBuilder.putPluginHeader(PluginProto.PluginHeaderKey.PLUGIN_ID_VALUE, pluginId);
packageBuilder.putPluginHeader(PluginProto.PluginHeaderKey.PLUGIN_TIMESTAMP_VALUE,
String.valueOf(System.currentTimeMillis()));
if (StringUtils.isNotEmpty(pluginRefere)) {
packageBuilder.putPluginHeader(PluginProto.PluginHeaderKey.PLUGIN_REFERER_VALUE, pluginRefere);
}
if (StringUtils.isNotEmpty(requestParams)) {
packageBuilder.setData(requestParams);
}
byte[] httpContent = packageBuilder.build().toByteArray();
String authKey = bean.getAuthKey();
if (StringUtils.isNotEmpty(authKey)) {
// AES 加密整个proto,通过http传输给plugin
// byte[] tsk = AESCrypto.generateTSKey(bean.getAuthKey());
byte[] tsk = bean.getAuthKey().getBytes(CharsetCoding.ISO_8859_1);
byte[] enPostContent = AESCrypto.encrypt(tsk, httpContent);
httpContent = enPostContent;
}
byte[] httpResponse = ZalyHttpClient.getInstance().postBytes(pluginUrl, httpContent);
if (httpResponse != null) {
ApiPluginProxyProto.ApiPluginProxyResponse response = ApiPluginProxyProto.ApiPluginProxyResponse
.newBuilder().setData(ByteString.copyFrom(httpResponse)).build();
commandResponse.setParams(response.toByteArray());// httpResposne,callback方法的回调方法参数
}
errCode = ErrorCode2.SUCCESS;
}
} else {
errCode = ErrorCode2.ERROR_PARAMETER;
}
} catch (Exception e) {
errCode = ErrorCode2.ERROR_SYSTEMERROR;
LogUtils.requestErrorLog(logger, command, e);
}
return commandResponse.setErrCode2(errCode);
}
@ApiModelProperty(hidden = true)
public boolean isValid() {
return !StringUtils.isAnyBlank(username, email, password, confirmPassword);
}
@Override
public List<RouterInfo> getRouterInfoList(Context context, InboundPackage inboundPackage){
Proxy.Topic dstTopic;
Proxy.Topic srcTopic;
if(Dict.SERVICENAME_INFERENCE.equals(context.getServiceName())) {
Proxy.Topic.Builder topicBuilder = Proxy.Topic.newBuilder();
dstTopic = topicBuilder.setPartyId(selfCoordinator).
setRole(inferenceServiceName)
.setName(Dict.PARTNER_PARTY_NAME)
.build();
srcTopic = topicBuilder.setPartyId(selfCoordinator).
setRole(Dict.SELF_PROJECT_NAME)
.setName(Dict.PARTNER_PARTY_NAME)
.build();
} else { // default unaryCall
Proxy.Packet sourcePacket = (Proxy.Packet) inboundPackage.getBody();
dstTopic = sourcePacket.getHeader().getDst();
srcTopic = sourcePacket.getHeader().getSrc();
}
Preconditions.checkNotNull(dstTopic, "dstTopic cannot be null");
if(!isAllowed(srcTopic, dstTopic)){
logger.warn("from {} to {} is not allowed!", srcTopic, dstTopic);
return null;
}
List<RouterInfo> routeList = topicEndpointMapping.getOrDefault(dstTopic, null);
if (routeList != null) {
return routeList;
}
// to get route list from routeTable
String topicName = dstTopic.getName();
String coordinator = dstTopic.getPartyId();
String serviceName = dstTopic.getRole();
if (StringUtils.isAnyBlank(topicName, coordinator, serviceName)) {
throw new IllegalArgumentException("one of dstTopic name, coordinator, role is null. dstTopic: " + dstTopic);
}
Map<String, List<BasicMeta.Endpoint>> serviceTable =
routeTable.getOrDefault(coordinator, routeTable.getOrDefault(DEFAULT, null));
if (serviceTable == null) {
throw new IllegalStateException("No available endpoint for the coordinator: " + coordinator +
". Considering adding a default endpoint?");
}
List<BasicMeta.Endpoint> endpoints =
serviceTable.getOrDefault(serviceName, serviceTable.getOrDefault(DEFAULT, null));
if (endpoints == null || endpoints.isEmpty()) {
throw new IllegalStateException("No available endpoint for this service: " + serviceName +
". Considering adding a default endpoint, or check if the list is empty?");
}
routeList = new ArrayList<>();
for(BasicMeta.Endpoint epoint: endpoints){
RouterInfo router = new RouterInfo();
// ip is first priority
if(!epoint.getIp().isEmpty()) {
router.setHost(epoint.getIp());
}else{
router.setHost(epoint.getHostname());
}
router.setPort(epoint.getPort());
routeList.add(router);
}
topicEndpointMapping.put(dstTopic, routeList);
return routeList;
}