use of org.apache.commons.lang3.StringUtils.defaultIfBlank in project mapton by trixon.
the class MPoiManager method initListeners.
private void initListeners() {
mDelayedResetRunner = new DelayedResetRunner(200, () -> {
var allPois = new ArrayList<MPoi>();
Lookup.getDefault().lookupAll(MPoiProvider.class).forEach(poiProvider -> {
try {
for (var poi : poiProvider.getPois()) {
poi.setCategory(StringUtils.defaultIfBlank(poi.getCategory(), "_DEFAULT"));
poi.setProvider(poiProvider.getName());
poi.setZoom(poi.getZoom() != null ? poi.getZoom() : 0.9);
allPois.add(poi);
}
} catch (Exception e) {
System.err.println("Failed to load POI from " + poiProvider.getName());
}
});
getAllItems().setAll(allPois);
// Hand off PoiCategoryCheckTreeView to return refreshed categories
mTrigRefreshCategoriesProperty.set(System.currentTimeMillis());
});
Lookup.getDefault().lookupResult(MPoiProvider.class).addLookupListener(lookupEvent -> {
mDelayedResetRunner.reset();
});
// Gets updated in PoiCategoryCheckTreeView
mCategoriesProperty.addListener((observable, oldValue, newValue) -> {
applyFilter();
});
selectedItemProperty().addListener((observable, oldValue, newValue) -> {
sendObjectProperties(newValue);
});
MBookmarkManager.getInstance().getItems().addListener((ListChangeListener.Change<? extends MBookmark> c) -> {
refresh();
});
mPolygonFilterManager.addListener(() -> {
refresh();
});
}
use of org.apache.commons.lang3.StringUtils.defaultIfBlank in project jun_springboot_api_service by wujun728.
the class SwaggerProvider method swaggerJson.
@ResponseBody
public SwaggerEntity swaggerJson() {
this.DEFINITION_MAP.clear();
List<ApiInfo> infos = requestMagicDynamicRegistry.mappings();
SwaggerEntity swaggerEntity = new SwaggerEntity();
swaggerEntity.setInfo(info);
swaggerEntity.setBasePath(this.basePath);
for (ApiInfo info : infos) {
String groupName = magicResourceService.getGroupName(info.getGroupId()).replace("/", "-");
String requestPath = PathUtils.replaceSlash(this.prefix + magicResourceService.getGroupPath(info.getGroupId()) + "/" + info.getPath());
SwaggerEntity.Path path = new SwaggerEntity.Path(info.getId());
path.addTag(groupName);
boolean hasBody = false;
try {
List<Map<String, Object>> parameters = parseParameters(info);
hasBody = parameters.stream().anyMatch(it -> VAR_NAME_REQUEST_BODY.equals(it.get("in")));
BaseDefinition baseDefinition = info.getRequestBodyDefinition();
if (hasBody && baseDefinition != null) {
doProcessDefinition(baseDefinition, info, groupName, "root_", "request", 0);
}
parameters.forEach(path::addParameter);
if (this.persistenceResponseBody) {
baseDefinition = info.getResponseBodyDefinition();
if (baseDefinition != null) {
Map responseMap = parseResponse(info);
if (!responseMap.isEmpty()) {
path.setResponses(responseMap);
doProcessDefinition(baseDefinition, info, groupName, "root_" + baseDefinition.getName(), "response", 0);
}
} else {
path.addResponse("200", JsonUtils.readValue(Objects.toString(info.getResponseBody(), BODY_EMPTY), Object.class));
}
}
} catch (Exception ignored) {
}
if (hasBody) {
path.addConsume("application/json");
} else {
path.addConsume("*/*");
}
path.addProduce("application/json");
path.setSummary(info.getName());
path.setDescription(StringUtils.defaultIfBlank(info.getDescription(), info.getName()));
swaggerEntity.addPath(requestPath, info.getMethod(), path);
}
if (this.DEFINITION_MAP.size() > 0) {
Set<Map.Entry> entries = ((Map) this.DEFINITION_MAP).entrySet();
for (Map.Entry entry : entries) {
swaggerEntity.addDefinitions(Objects.toString(entry.getKey()), entry.getValue());
}
}
return swaggerEntity;
}
use of org.apache.commons.lang3.StringUtils.defaultIfBlank in project jun_springboot_api_service by wujun728.
the class RequestHandler method doValidate.
private Map<String, Object> doValidate(String scriptName, String comment, List<? extends BaseDefinition> validateParameters, Map<String, Object> parameters, JsonCode jsonCode, boolean disabledUnknownParameter) {
parameters = parameters != null ? parameters : EMPTY_MAP;
if (CollectionUtils.isEmpty(validateParameters)) {
return parameters;
}
if (disabledUnknownParameter) {
removeUnknownKey(parameters, validateParameters);
}
for (BaseDefinition parameter : validateParameters) {
if (parameter.getDataType() == DataType.Any) {
continue;
}
// 针对requestBody多层级的情况
if (DataType.Object == parameter.getDataType()) {
if (doValidateBody(comment, parameter, parameters, jsonCode, Map.class)) {
continue;
}
doValidate(scriptName, VAR_NAME_REQUEST_BODY, parameter.getChildren(), (Map) parameters.get(parameter.getName()), jsonCode, disabledUnknownParameter);
} else if (DataType.Array == parameter.getDataType()) {
if (doValidateBody(comment, parameter, parameters, jsonCode, List.class)) {
continue;
}
List<Object> list = (List) parameters.get(parameter.getName());
if (list != null) {
List<Map<String, Object>> newList = list.stream().map(it -> doValidate(scriptName, VAR_NAME_REQUEST_BODY, parameter.getChildren(), new HashMap<String, Object>() {
{
put(Constants.EMPTY, it);
}
}, jsonCode, disabledUnknownParameter)).collect(Collectors.toList());
for (int i = 0, size = newList.size(); i < size; i++) {
list.set(i, newList.get(i).get(Constants.EMPTY));
}
}
} else if (StringUtils.isNotBlank(parameter.getName()) || parameters.containsKey(parameter.getName())) {
boolean isFile = parameter.getDataType() == DataType.MultipartFile || parameter.getDataType() == DataType.MultipartFiles;
String requestValue = StringUtils.defaultIfBlank(Objects.toString(parameters.get(parameter.getName()), Constants.EMPTY), Objects.toString(parameter.getDefaultValue(), Constants.EMPTY));
if (StringUtils.isBlank(requestValue) && !isFile) {
if (!parameter.isRequired()) {
continue;
}
throw new ValidateException(jsonCode, StringUtils.defaultIfBlank(parameter.getError(), String.format("%s[%s]为必填项", comment, parameter.getName())));
}
try {
Object value = convertValue(parameter.getDataType(), parameter.getName(), requestValue);
if (isFile && parameter.isRequired()) {
if (value == null || (parameter.getDataType() == DataType.MultipartFiles && ((List<?>) value).isEmpty())) {
throw new ValidateException(jsonCode, StringUtils.defaultIfBlank(parameter.getError(), String.format("%s[%s]为必填项", comment, parameter.getName())));
}
}
// 正则验证
if (VALIDATE_TYPE_PATTERN.equals(parameter.getValidateType())) {
String expression = parameter.getExpression();
if (StringUtils.isNotBlank(expression) && !PatternUtils.match(Objects.toString(value, Constants.EMPTY), expression)) {
throw new ValidateException(jsonCode, StringUtils.defaultIfBlank(parameter.getError(), String.format("%s[%s]不满足正则表达式", comment, parameter.getName())));
}
}
parameters.put(parameter.getName(), value);
} catch (ValidateException ve) {
throw ve;
} catch (Exception e) {
throw new ValidateException(jsonCode, StringUtils.defaultIfBlank(parameter.getError(), String.format("%s[%s]不合法", comment, parameter.getName())));
}
}
}
// 取出表达式验证的参数
List<BaseDefinition> validates = validateParameters.stream().filter(it -> VALIDATE_TYPE_EXPRESSION.equals(it.getValidateType()) && StringUtils.isNotBlank(it.getExpression())).collect(Collectors.toList());
for (BaseDefinition parameter : validates) {
MagicScriptContext context = new MagicScriptContext();
// 将其他参数也放置脚本中,以实现“依赖”的情况
context.putMapIntoContext(parameters);
Object value = parameters.get(parameter.getName());
if (value != null) {
context.setScriptName(scriptName);
// 设置自身变量
context.set(EXPRESSION_DEFAULT_VAR_NAME, value);
if (!BooleanLiteral.isTrue(ScriptManager.executeExpression(parameter.getExpression(), context))) {
throw new ValidateException(jsonCode, StringUtils.defaultIfBlank(parameter.getError(), String.format("%s[%s]不满足表达式", comment, parameter.getName())));
}
}
}
return parameters;
}
use of org.apache.commons.lang3.StringUtils.defaultIfBlank in project jun_springboot_api_service by wujun728.
the class MagicWorkbenchHandler method onLogin.
@Message(MessageType.LOGIN)
public void onLogin(MagicConsoleSession session, String token, String clientId) {
session.setClientId(clientId);
MagicUser user = null;
try {
user = authorizationInterceptor.getUserByToken(token);
} catch (Exception e) {
if (!authorizationInterceptor.requireLogin()) {
user = guest;
}
}
if (user != null) {
String ip = Optional.ofNullable(session.getWebSocketSession().getRemoteAddress()).map(it -> it.getAddress().getHostAddress()).orElse("unknown");
HttpHeaders headers = session.getWebSocketSession().getHandshakeHeaders();
ip = IpUtils.getRealIP(ip, headers::getFirst, null);
session.setAttribute(Constants.WEBSOCKET_ATTRIBUTE_USER_ID, user.getId());
session.setAttribute(Constants.WEBSOCKET_ATTRIBUTE_USER_IP, StringUtils.defaultIfBlank(ip, "unknown"));
session.setAttribute(Constants.WEBSOCKET_ATTRIBUTE_USER_NAME, user.getUsername());
session.setActivateTime(System.currentTimeMillis());
synchronized (MagicWorkbenchHandler.class) {
if (WebSocketSessionManager.getConsoleSession(clientId) != null) {
WebSocketSessionManager.sendBySession(session, WebSocketSessionManager.buildMessage(MessageType.LOGIN_RESPONSE, "-1"));
return;
}
WebSocketSessionManager.add(session);
}
WebSocketSessionManager.sendBySession(session, WebSocketSessionManager.buildMessage(MessageType.LOGIN_RESPONSE, "1", session.getAttributes()));
List<Map<String, Object>> messages = getOnlineUsers();
if (!messages.isEmpty()) {
WebSocketSessionManager.sendByClientId(session.getClientId(), WebSocketSessionManager.buildMessage(MessageType.ONLINE_USERS, messages));
}
WebSocketSessionManager.sendToMachine(MessageType.SEND_ONLINE, session.getClientId());
WebSocketSessionManager.sendToOther(session.getClientId(), MessageType.USER_LOGIN, session.getAttributes());
} else {
WebSocketSessionManager.sendBySession(session, WebSocketSessionManager.buildMessage(MessageType.LOGIN_RESPONSE, "0"));
}
}
use of org.apache.commons.lang3.StringUtils.defaultIfBlank in project dhis2-core by dhis2.
the class TrackedEntityRegistrationSMSListener method postProcess.
// -------------------------------------------------------------------------
// IncomingSmsListener implementation
// -------------------------------------------------------------------------
@Override
protected void postProcess(IncomingSms sms, SMSCommand smsCommand, Map<String, String> parsedMessage) {
String message = sms.getText();
Date date = SmsUtils.lookForDate(message);
String senderPhoneNumber = StringUtils.replace(sms.getOriginator(), "+", "");
Collection<OrganisationUnit> orgUnits = getOrganisationUnits(sms);
Program program = smsCommand.getProgram();
OrganisationUnit orgUnit = SmsUtils.selectOrganisationUnit(orgUnits, parsedMessage, smsCommand);
if (!programService.hasOrgUnit(program, orgUnit)) {
sendFeedback(SMSCommand.NO_OU_FOR_PROGRAM, senderPhoneNumber, WARNING);
throw new SMSParserException(SMSCommand.NO_OU_FOR_PROGRAM);
}
TrackedEntityInstance trackedEntityInstance = new TrackedEntityInstance();
trackedEntityInstance.setOrganisationUnit(orgUnit);
trackedEntityInstance.setTrackedEntityType(trackedEntityTypeService.getTrackedEntityByName(smsCommand.getProgram().getTrackedEntityType().getName()));
Set<TrackedEntityAttributeValue> patientAttributeValues = new HashSet<>();
smsCommand.getCodes().stream().filter(code -> parsedMessage.containsKey(code.getCode())).forEach(code -> {
TrackedEntityAttributeValue trackedEntityAttributeValue = this.createTrackedEntityAttributeValue(parsedMessage, code, trackedEntityInstance);
patientAttributeValues.add(trackedEntityAttributeValue);
});
long trackedEntityInstanceId = 0;
if (patientAttributeValues.size() > 0) {
trackedEntityInstanceId = trackedEntityInstanceService.createTrackedEntityInstance(trackedEntityInstance, patientAttributeValues);
} else {
sendFeedback("No TrackedEntityAttribute found", senderPhoneNumber, WARNING);
}
TrackedEntityInstance tei = trackedEntityInstanceService.getTrackedEntityInstance(trackedEntityInstanceId);
programInstanceService.enrollTrackedEntityInstance(tei, smsCommand.getProgram(), new Date(), date, orgUnit);
sendFeedback(StringUtils.defaultIfBlank(smsCommand.getSuccessMessage(), SUCCESS_MESSAGE + tei.getUid()), senderPhoneNumber, INFO);
update(sms, SmsMessageStatus.PROCESSED, true);
}
Aggregations