use of org.apache.commons.lang3.StringUtils.substring in project mule-migration-assistant by mulesoft.
the class NotFilter method negateValidator.
public Element negateValidator(Element validator, MigrationReport report, Element original) {
if ("is-true".equals(validator.getName())) {
validator.setName("is-false");
} else if ("is-false".equals(validator.getName())) {
validator.setName("is-true");
} else if ("matches-regex".equals(validator.getName())) {
Attribute regexAttr = validator.getAttribute("regex");
if (regexAttr.getValue().startsWith("(?!") && regexAttr.getValue().endsWith(")")) {
regexAttr.setValue(StringUtils.substring(regexAttr.getValue(), 3, -1));
} else {
regexAttr.setValue("(?!" + regexAttr.getValue() + ")");
}
} else if ("any".equals(validator.getName())) {
validator.setName("all");
validator.getChildren().forEach(c -> negateValidator(c, report, original));
} else if ("all".equals(validator.getName())) {
validator.setName("any");
validator.getChildren().forEach(c -> negateValidator(c, report, original));
} else {
report.report("filters.negated", original, validator);
}
return validator;
}
use of org.apache.commons.lang3.StringUtils.substring in project solo by 88250.
the class Markdowns method toHTML.
/**
* Converts the specified markdown text to HTML.
*
* @param markdownText the specified markdown text
* @return converted HTML, returns an empty string "" if the specified markdown text is "" or {@code null}, returns
* 'markdownErrorLabel' if exception
*/
public static String toHTML(final String markdownText) {
if (StringUtils.isBlank(markdownText)) {
return "";
}
final String cachedHTML = getHTML(markdownText);
if (null != cachedHTML) {
return cachedHTML;
}
final LangPropsService langPropsService = BeanManager.getInstance().getReference(LangPropsService.class);
final ExecutorService pool = Executors.newSingleThreadExecutor();
final long[] threadId = new long[1];
final Callable<String> call = () -> {
threadId[0] = Thread.currentThread().getId();
String html = null;
if (LUTE_AVAILABLE) {
try {
html = toHtmlByLute(markdownText);
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Failed to use Lute [" + LUTE_ENGINE_URL + "] for markdown [md=" + StringUtils.substring(markdownText, 0, 256) + "]: " + e.getMessage());
}
}
if (StringUtils.isBlank(html)) {
html = toHtmlByFlexmark(markdownText);
}
final Document doc = Jsoup.parseBodyFragment(html);
doc.select("a").forEach(a -> {
final String src = a.attr("href");
if (!StringUtils.startsWithIgnoreCase(src, Latkes.getServePath()) && !StringUtils.startsWithIgnoreCase(src, "#")) {
a.attr("target", "_blank");
}
a.removeAttr("id");
});
final List<Node> toRemove = new ArrayList<>();
doc.traverse(new NodeVisitor() {
@Override
public void head(final org.jsoup.nodes.Node node, int depth) {
if (node instanceof org.jsoup.nodes.TextNode) {
final org.jsoup.nodes.TextNode textNode = (org.jsoup.nodes.TextNode) node;
final org.jsoup.nodes.Node parent = textNode.parent();
if (parent instanceof Element) {
final Element parentElem = (Element) parent;
if (parentElem.tagName().equals("code") || parentElem.tagName().equals("pre")) {
return;
}
if (parentElem.tagName().equals("span") && StringUtils.startsWithIgnoreCase(parentElem.attr("class"), "hljs")) {
return;
}
String text = textNode.getWholeText();
text = Emotions.convert(text);
if (text.contains("@<a href=") || text.contains("<img")) {
final List<org.jsoup.nodes.Node> nodes = Parser.parseFragment(text, parentElem, "");
final int index = textNode.siblingIndex();
parentElem.insertChildren(index, nodes);
toRemove.add(node);
} else {
textNode.text(text);
}
}
}
}
@Override
public void tail(org.jsoup.nodes.Node node, int depth) {
}
});
toRemove.forEach(Node::remove);
doc.outputSettings().prettyPrint(false);
Images.qiniuImgProcessing(doc);
String ret = doc.body().html();
ret = StringUtils.trim(ret);
// cache it
putHTML(markdownText, ret);
return ret;
};
Stopwatchs.start("Md to HTML");
try {
final Future<String> future = pool.submit(call);
return future.get(MD_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (final TimeoutException e) {
LOGGER.log(Level.ERROR, "Markdown timeout [md=" + markdownText + "]");
Callstacks.printCallstack(Level.ERROR, new String[] { "org.b3log" }, null);
final Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (final Thread thread : threads) {
if (thread.getId() == threadId[0]) {
thread.stop();
break;
}
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Markdown failed [md=" + markdownText + "]", e);
} finally {
pool.shutdownNow();
Stopwatchs.end();
}
return langPropsService.get("contentRenderFailedLabel");
}
use of org.apache.commons.lang3.StringUtils.substring in project ebase-boot by ebase-projects.
the class DataScopeFilterInterceptor method getSqlFilter.
/**
* 获取数据过滤的SQL
*/
private String getSqlFilter(UserInfoDetails user, MappedStatement mappedStatement) throws Exception {
StringBuilder sqlFilter = new StringBuilder();
// 组合角色数据
String roleIds = user.getRoleId();
Set<Long> roleIdSet = new HashSet<>();
if (!StringUtils.isBlank(roleIds)) {
String[] roleIdStrs = StringUtils.split(roleIds, ",");
List<String> roleIdStrList = Arrays.asList(roleIdStrs);
if (roleIdStrList != null && roleIdStrList.size() != 0) {
roleIdStrList.forEach(p -> {
roleIdSet.add(Long.parseLong(p));
});
}
}
// 根据角色信息查询拥有的数据权限列表
List<RoleDataScopeModel> roleDataScopeModels = getDataScopeByRoleId(roleIdSet);
// 查询DataScopeFilter注释
Class<?> classType = Class.forName(mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf(".")));
String mName = mappedStatement.getId().substring(mappedStatement.getId().lastIndexOf(".") + 1, mappedStatement.getId().length());
for (Method method : classType.getDeclaredMethods()) {
if (method.isAnnotationPresent(DataScopeFilter.class) && mName.equals(method.getName())) {
DataScopeFilter dataFilter = method.getAnnotation(DataScopeFilter.class);
// 获取表的别名
String tableAlias = dataFilter.tableAlias();
if (StringUtils.isNotBlank(tableAlias)) {
tableAlias += ".";
}
// 设置优先级
if (roleDataScopeModels == null || roleDataScopeModels.size() == 0) {
if (getDataScopeLevel().equalsIgnoreCase("ALL")) {
// 默认全部
return "";
} else {
sqlFilter.append(" (");
sqlFilter.append(tableAlias).append(dataFilter.createBy()).append("=").append(user.getUserId());
sqlFilter.append(")");
return sqlFilter.toString();
}
}
// 根据type 分组
Map<Integer, List<RoleDataScopeModel>> roleDataScopeModelsByMap = roleDataScopeModels.stream().sorted(Comparator.comparing(RoleDataScopeModel::getScopeType)).collect(Collectors.groupingBy(RoleDataScopeModel::getScopeType));
if (roleDataScopeModelsByMap.containsKey(DataScopeViewEnum.ALL.getValue())) {
// 全部
return "";
}
// 部门集合
Set<Long> customDeptId = new HashSet<>();
// 是否包含自己
boolean isContainOwn = false;
if (roleDataScopeModelsByMap.containsKey(DataScopeViewEnum.CUSTOM.getValue())) {
// 自定义
List<RoleDataScopeModel> tmp = roleDataScopeModelsByMap.get(DataScopeViewEnum.CUSTOM.getValue());
if (tmp != null && tmp.size() > 0) {
for (RoleDataScopeModel roleDataScopeModel : tmp) {
if (roleDataScopeModel != null) {
String deptIdStrs = roleDataScopeModel.getDeptIds();
if (StringUtils.isNotBlank(deptIdStrs)) {
String[] split = StringUtils.substring(deptIdStrs, 1, deptIdStrs.length() - 1).split(",");
List<String> deptIdStrList = Arrays.asList(split);
Set<Long> customDeptIdTmp = deptIdStrList.stream().map(x -> (Long.parseLong(StringUtils.trim(x)))).collect(Collectors.toSet());
customDeptId.addAll(customDeptIdTmp);
}
}
}
}
}
if (roleDataScopeModelsByMap.containsKey(DataScopeViewEnum.OWN.getValue())) {
// 自己
isContainOwn = true;
}
if (roleDataScopeModelsByMap.containsKey(DataScopeViewEnum.DEPT.getValue())) {
// 部门
String deptIdStr = SecurityUtils.getUser().getDeptId();
if (!StringUtils.isBlank(deptIdStr)) {
long deptId = Long.parseLong(deptIdStr);
customDeptId.add(deptId);
}
}
if (roleDataScopeModelsByMap.containsKey(DataScopeViewEnum.DEPT_CHILD.getValue())) {
// 部门及子部门
String deptIdStr = SecurityUtils.getUser().getDeptId();
if (!StringUtils.isBlank(deptIdStr)) {
long deptId = Long.parseLong(deptIdStr);
customDeptId.add(deptId);
List<Long> list = getSubDeptBydeptId(deptId);
customDeptId.addAll(list);
}
}
sqlFilter.append(" (");
// 部门ID列表
if (CollUtil.isNotEmpty(customDeptId)) {
sqlFilter.append(tableAlias).append(dataFilter.createDept());
sqlFilter.append(" in(").append(StringUtils.join(customDeptId, ",")).append(")");
}
// 查询本人数据
if (CollUtil.isNotEmpty(customDeptId)) {
if (isContainOwn) {
sqlFilter.append(" or ");
sqlFilter.append(tableAlias).append(dataFilter.createBy()).append("=").append(user.getUserId());
}
} else {
if (isContainOwn) {
sqlFilter.append(tableAlias).append(dataFilter.createBy()).append("=").append(user.getUserId());
}
}
sqlFilter.append(")");
break;
}
}
return sqlFilter.toString();
}
use of org.apache.commons.lang3.StringUtils.substring in project aem-core-wcm-components by Adobe-Marketing-Cloud.
the class ExperienceFragmentDataImpl method getLocalizedFragmentVariationPath.
/**
* Returns the localized path of the experience fragment variation if the experience fragment resource is defined
* in a template.
*
* @return Localized experience fragment variation path
* @see ExperienceFragment#getLocalizedFragmentVariationPath()
*/
@Nullable
public String getLocalizedFragmentVariationPath() {
if (localizedFragmentVariationPath != null) {
return localizedFragmentVariationPath;
}
// get the configured fragment variation path
String fragmentVariationPath = resource.getValueMap().get(ExperienceFragment.PN_FRAGMENT_VARIATION_PATH, String.class);
if (currentPage != null && inTemplate()) {
final Resource pageResource = Optional.ofNullable(currentPage).map(p -> p.adaptTo(Resource.class)).orElse(null);
final String currentPageRootPath = pageResource != null ? LocalizationUtils.getLocalizationRoot(pageResource, resourceResolver, languageManager, relationshipManager) : null;
// we should use getLocalizationRoot instead of getXfLocalizationRoot once the XF UI supports creating Live and Language Copies
String xfRootPath = getXfLocalizationRoot(fragmentVariationPath, currentPageRootPath);
if (StringUtils.isNotEmpty(currentPageRootPath) && StringUtils.isNotEmpty(xfRootPath)) {
String xfRelativePath = StringUtils.substring(fragmentVariationPath, xfRootPath.length());
String localizedXfRootPath = StringUtils.replace(currentPageRootPath, CONTENT_ROOT, ExperienceFragmentsConstants.CONTENT_PATH, 1);
localizedFragmentVariationPath = StringUtils.join(localizedXfRootPath, xfRelativePath, PATH_DELIMITER_CHAR, NN_CONTENT);
}
}
String xfContentPath = String.join(Character.toString(PATH_DELIMITER_CHAR), fragmentVariationPath, NN_CONTENT);
if (!resourceExists(localizedFragmentVariationPath) && resourceExists(xfContentPath)) {
localizedFragmentVariationPath = xfContentPath;
}
if (!isExperienceFragmentVariation(localizedFragmentVariationPath)) {
localizedFragmentVariationPath = null;
}
return localizedFragmentVariationPath;
}
use of org.apache.commons.lang3.StringUtils.substring in project inception by inception-project.
the class ConceptFeatureEditor method getCandidates.
private List<KBHandle> getCandidates(IModel<AnnotatorState> aStateModel, AnnotationActionHandler aHandler, String aInput) {
if (aInput == null) {
return emptyList();
}
String input = aInput;
// Extract filter on the description
final String descriptionFilter;
if (input.contains("::")) {
descriptionFilter = substringAfter(input, "::").trim();
input = substringBefore(input, "::");
} else {
descriptionFilter = null;
}
// Extract exact match filter on the query
boolean labelFilter = false;
String trimmedInput = input.trim();
if (trimmedInput.length() > 2 && trimmedInput.startsWith("\"") && trimmedInput.endsWith("\"")) {
input = StringUtils.substring(trimmedInput, 1, -1).trim();
labelFilter = true;
}
final String finalInput = input;
List<KBHandle> choices;
try {
AnnotationFeature feat = getModelObject().feature;
ConceptFeatureTraits traits = readFeatureTraits(feat);
String repoId = traits.getRepositoryId();
// Check if kb is actually enabled
if (!(repoId == null || kbService.isKnowledgeBaseEnabled(feat.getProject(), repoId))) {
return Collections.emptyList();
}
// If there is a selection, we try obtaining its text from the CAS and use it as an
// additional item in the query. Note that there is not always a mention, e.g. when the
// feature is used in a document-level annotations.
CAS cas = aHandler != null ? aHandler.getEditorCas() : null;
String mention = aStateModel != null ? aStateModel.getObject().getSelection().getText() : null;
int mentionBegin = aStateModel != null ? aStateModel.getObject().getSelection().getBegin() : -1;
choices = clService.getLinkingInstancesInKBScope(traits.getRepositoryId(), traits.getScope(), traits.getAllowedValueType(), finalInput, mention, mentionBegin, cas, feat.getProject());
} catch (Exception e) {
choices = asList(new KBHandle("http://ERROR", "ERROR", e.getMessage(), "en"));
error("An error occurred while retrieving entity candidates: " + e.getMessage());
LOG.error("An error occurred while retrieving entity candidates", e);
RequestCycle.get().find(IPartialPageRequestHandler.class).ifPresent(target -> target.addChildren(getPage(), IFeedback.class));
}
if (labelFilter) {
choices = choices.stream().filter(kb -> containsIgnoreCase(kb.getUiLabel(), finalInput)).collect(Collectors.toList());
}
if (isNotBlank(descriptionFilter)) {
choices = choices.stream().filter(kb -> containsIgnoreCase(kb.getDescription(), descriptionFilter)).collect(Collectors.toList());
}
return choices.stream().limit(entityLinkingProperties.getCandidateDisplayLimit()).collect(Collectors.toList());
}
Aggregations