List of usage examples for org.apache.commons.lang StringUtils containsIgnoreCase
public static boolean containsIgnoreCase(String str, String searchStr)
Checks if String contains a search String irrespective of case, handling null
.
From source file:org.apache.zeppelin.tajo.TajoInterpreter.java
private InterpreterResult executeSql(String sql) { try {//from w w w . ja va 2 s . c o m if (exceptionOnConnect != null) { return new InterpreterResult(Code.ERROR, exceptionOnConnect.getMessage()); } statement = connection.createStatement(); StringBuilder msg = null; if (StringUtils.containsIgnoreCase(sql, "EXPLAIN ")) { //return the explain as text, make this visual explain later msg = new StringBuilder(); } else { msg = new StringBuilder("%table "); } ResultSet res = statement.executeQuery(sql); try { ResultSetMetaData md = res.getMetaData(); for (int i = 1; i < md.getColumnCount() + 1; i++) { if (i == 1) { msg.append(md.getColumnName(i)); } else { msg.append("\t" + md.getColumnName(i)); } } msg.append("\n"); while (res.next()) { for (int i = 1; i < md.getColumnCount() + 1; i++) { msg.append(res.getString(i) + "\t"); } msg.append("\n"); } } finally { try { res.close(); statement.close(); } finally { statement = null; } } InterpreterResult interpreterResult = new InterpreterResult(Code.SUCCESS, msg.toString()); return interpreterResult; } catch (SQLException ex) { logger.error("Can not run " + sql, ex); return new InterpreterResult(Code.ERROR, ex.getMessage()); } }
From source file:org.artifactory.webapp.wicket.page.home.settings.maven.MavenSettingsPanel.java
private T getDefaultChoice(final boolean isRelease, final boolean isSnapshot, final boolean isPlugin, final boolean isRemote) { DefaultOptionSelector<RepoDescriptor> selector = new DefaultOptionSelector<RepoDescriptor>() { @Override/*from w w w . j av a2 s . c o m*/ public boolean acceptedAsDefault(RepoDescriptor virtualRepoDescriptor) { boolean canBeDefault = true; String key = virtualRepoDescriptor.getKey(); if (isRelease && !repoKeyContains(key, "release")) { canBeDefault = false; } if (isSnapshot && !repoKeyContains(key, "snapshot")) { canBeDefault = false; } if (isPlugin && !repoKeyContains(key, "plugin")) { canBeDefault = false; } if (isRemote && !repoKeyContains(key, "remote")) { canBeDefault = false; } return canBeDefault; } private boolean repoKeyContains(String repoKey, String idText) { return StringUtils.containsIgnoreCase(repoKey, idText); } }; for (T virtualRepoDescriptor : virtualRepoDescriptors) { if (selector.acceptedAsDefault(virtualRepoDescriptor)) { return virtualRepoDescriptor; } } return virtualRepoDescriptors.get(0); }
From source file:org.b3log.solo.model.UserExt.java
/** * Checks whether the specified name is invalid. * <p>//w ww. j a v a2s . co m * A valid user name: * <ul> * <li>length [1, 20]</li> * <li>content {a-z, A-Z, 0-9}</li> * <li>Not contains "admin"/"Admin"</li> * </ul> * </p> * * @param name the specified name * @return {@code true} if it is invalid, returns {@code false} otherwise */ public static boolean invalidUserName(final String name) { final int length = name.length(); if (length < MIN_USER_NAME_LENGTH || length > MAX_USER_NAME_LENGTH) { return true; } char c; for (int i = 0; i < length; i++) { c = name.charAt(i); if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '0' <= c && c <= '9') { continue; } return true; } return StringUtils.containsIgnoreCase(name, "admin"); }
From source file:org.b3log.symphony.event.ArticleAddNotifier.java
@Override public void action(final Event<JSONObject> event) throws EventException { final JSONObject data = event.getData(); LOGGER.log(Level.TRACE, "Processing an event [type={0}, data={1}]", event.getType(), data); try {/* www .j ava 2 s. com*/ final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE); final String articleId = originalArticle.optString(Keys.OBJECT_ID); final String articleAuthorId = originalArticle.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject articleAuthor = userQueryService.getUser(articleAuthorId); final String articleAuthorName = articleAuthor.optString(User.USER_NAME); final Set<String> requisiteAtUserPermissions = new HashSet<>(); requisiteAtUserPermissions.add(Permission.PERMISSION_ID_C_COMMON_AT_USER); final boolean hasAtUserPerm = roleQueryService.userHasPermissions(articleAuthorId, requisiteAtUserPermissions); final Set<String> atedUserIds = new HashSet<>(); if (hasAtUserPerm) { // 'At' Notification final String articleContent = originalArticle.optString(Article.ARTICLE_CONTENT); final Set<String> atUserNames = userQueryService.getUserNames(articleContent); atUserNames.remove(articleAuthorName); // Do not notify the author itself for (final String userName : atUserNames) { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { LOGGER.log(Level.WARN, "Not found user by name [{0}]", userName); continue; } final JSONObject requestJSONObject = new JSONObject(); final String atedUserId = user.optString(Keys.OBJECT_ID); requestJSONObject.put(Notification.NOTIFICATION_USER_ID, atedUserId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addAtNotification(requestJSONObject); atedUserIds.add(atedUserId); } } final String tags = originalArticle.optString(Article.ARTICLE_TAGS); // 'following - user' Notification if (Article.ARTICLE_TYPE_C_DISCUSSION != originalArticle.optInt(Article.ARTICLE_TYPE) && Article.ARTICLE_ANONYMOUS_C_PUBLIC == originalArticle.optInt(Article.ARTICLE_ANONYMOUS) && !Tag.TAG_TITLE_C_SANDBOX.equals(tags) && !StringUtils.containsIgnoreCase(tags, Symphonys.get("systemAnnounce"))) { final JSONObject followerUsersResult = followQueryService.getFollowerUsers( UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL, articleAuthorId, 1, Integer.MAX_VALUE); final List<JSONObject> followerUsers = (List<JSONObject>) followerUsersResult.opt(Keys.RESULTS); for (final JSONObject followerUser : followerUsers) { final JSONObject requestJSONObject = new JSONObject(); final String followerUserId = followerUser.optString(Keys.OBJECT_ID); if (atedUserIds.contains(followerUserId)) { continue; } requestJSONObject.put(Notification.NOTIFICATION_USER_ID, followerUserId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addFollowingUserNotification(requestJSONObject); } } // Timeline final String articleTitle = Escapes.escapeHTML(originalArticle.optString(Article.ARTICLE_TITLE)); final String articlePermalink = Latkes.getServePath() + originalArticle.optString(Article.ARTICLE_PERMALINK); final JSONObject timeline = new JSONObject(); timeline.put(Common.USER_ID, articleAuthorId); timeline.put(Common.TYPE, Article.ARTICLE); String content = langPropsService.get("timelineArticleAddLabel"); if (Article.ARTICLE_ANONYMOUS_C_PUBLIC == originalArticle.optInt(Article.ARTICLE_ANONYMOUS)) { content = content.replace("{user}", "<a target='_blank' rel='nofollow' href='" + Latkes.getServePath() + "/member/" + articleAuthorName + "'>" + articleAuthorName + "</a>"); } else { content = content.replace("{user}", UserExt.ANONYMOUS_USER_NAME); } content = content.replace("{article}", "<a target='_blank' rel='nofollow' href='" + articlePermalink + "'>" + articleTitle + "</a>"); content = Emotions.convert(content); timeline.put(Common.CONTENT, content); timelineMgmtService.addTimeline(timeline); // 'Broadcast' / 'Book' Notification if (Article.ARTICLE_TYPE_C_CITY_BROADCAST == originalArticle.optInt(Article.ARTICLE_TYPE) || (Article.ARTICLE_TYPE_C_BOOK == originalArticle.optInt(Article.ARTICLE_TYPE) && !articleAuthorName.equals("book_share"))) { final String city = originalArticle.optString(Article.ARTICLE_CITY); if (StringUtils.isNotBlank(city)) { final JSONObject requestJSONObject = new JSONObject(); requestJSONObject.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, 1); requestJSONObject.put(Pagination.PAGINATION_PAGE_SIZE, Integer.MAX_VALUE); requestJSONObject.put(Pagination.PAGINATION_WINDOW_SIZE, Integer.MAX_VALUE); final long latestLoginTime = DateUtils.addDays(new Date(), -15).getTime(); requestJSONObject.put(UserExt.USER_LATEST_LOGIN_TIME, latestLoginTime); requestJSONObject.put(UserExt.USER_CITY, city); final JSONObject result = userQueryService.getUsersByCity(requestJSONObject); final JSONArray users = result.optJSONArray(User.USERS); for (int i = 0; i < users.length(); i++) { final String userId = users.optJSONObject(i).optString(Keys.OBJECT_ID); if (userId.equals(articleAuthorId)) { continue; } final JSONObject notification = new JSONObject(); notification.put(Notification.NOTIFICATION_USER_ID, userId); notification.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addBroadcastNotification(notification); } LOGGER.info("City [" + city + "] broadcast [users=" + users.length() + "]"); } } // 'Sys Announce' Notification if (StringUtils.containsIgnoreCase(tags, Symphonys.get("systemAnnounce"))) { final long latestLoginTime = DateUtils.addDays(new Date(), -15).getTime(); final JSONObject result = userQueryService.getLatestLoggedInUsers(latestLoginTime, 1, Integer.MAX_VALUE, Integer.MAX_VALUE); final JSONArray users = result.optJSONArray(User.USERS); for (int i = 0; i < users.length(); i++) { final String userId = users.optJSONObject(i).optString(Keys.OBJECT_ID); final JSONObject notification = new JSONObject(); notification.put(Notification.NOTIFICATION_USER_ID, userId); notification.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addSysAnnounceArticleNotification(notification); } LOGGER.info("System announcement [" + articleTitle + "] broadcast [users=" + users.length() + "]"); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Sends the article add notification failed", e); } }
From source file:org.b3log.symphony.model.Link.java
/** * Checks whether the specified link address in blacklist. * * @param linkAddr the specified link address * @return {@code true} if it in blacklist, otherwise returns {@code false} */// w w w.jav a 2s. c om public static final boolean inAddrBlacklist(final String linkAddr) { for (final String site : LINK_ADDR_C_BLACKLIST) { if (StringUtils.containsIgnoreCase(linkAddr, site)) { return true; } } return false; }
From source file:org.b3log.symphony.model.Tag.java
/** * Checks the specified tag string whether contains the reserved tags. * * @param tagStr the specified tag string * @return {@code true} if it contains, returns {@code false} otherwise *//*w w w. ja v a2 s . c o m*/ public static boolean containsReservedTags(final String tagStr) { for (final String reservedTag : Symphonys.RESERVED_TAGS) { if (StringUtils.containsIgnoreCase(tagStr, reservedTag)) { return true; } } return false; }
From source file:org.b3log.symphony.model.Tag.java
/** * Normalizes the specified title. For example, Normalizes "JS" to "JavaScript. * * @param title the specified title/*from w ww .ja v a2 s.co m*/ * @return normalized title */ private static String normalize(final String title) { final TagCache cache = LatkeBeanManagerImpl.getInstance().getReference(TagCache.class); final List<JSONObject> iconTags = cache.getIconTags(Integer.MAX_VALUE); Collections.sort(iconTags, new Comparator<JSONObject>() { @Override public int compare(final JSONObject t1, final JSONObject t2) { final String u1Title = t1.optString(Tag.TAG_T_TITLE_LOWER_CASE); final String u2Title = t2.optString(Tag.TAG_T_TITLE_LOWER_CASE); return u1Title.length() - u2Title.length(); } }); for (final JSONObject iconTag : iconTags) { final String iconTagTitle = iconTag.optString(Tag.TAG_TITLE); if (iconTagTitle.length() < 2) { continue; } if (StringUtils.containsIgnoreCase(title, iconTagTitle)) { return iconTagTitle; } } for (final Map.Entry<String, Set<String>> entry : NORMALIZE_MAPPINGS.entrySet()) { final Set<String> oddTitles = entry.getValue(); for (final String oddTitle : oddTitles) { if (StringUtils.equalsIgnoreCase(title, oddTitle)) { return entry.getKey(); } } } return title; }
From source file:org.b3log.symphony.processor.IPFSProcessor.java
/** * Publishes article markdown files to IPFS. * * @param request the specified HTTP servlet request * @param response the specified HTTP servlet response * @param context the specified HTTP request context * @throws Exception exception/* ww w. j av a 2 s . c o m*/ */ @RequestProcessing(value = "/cron/ipfs/articles/publish", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = StopwatchEndAdvice.class) public void publishArticles(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) throws Exception { final String key = Symphonys.get("keyOfSymphony"); if (!key.equals(request.getParameter("key"))) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } context.renderJSON().renderTrueResult(); final String dir = Symphonys.get("ipfs.dir"); final String bin = Symphonys.get("ipfs.bin"); if (StringUtils.isBlank(dir) || StringUtils.isBlank(bin)) { return; } String output = Execs.exec(bin + " add -r " + dir); if (StringUtils.isBlank(output) || !StringUtils.containsIgnoreCase(output, "added")) { LOGGER.log(Level.ERROR, "Executes [ipfs add] failed: " + output); return; } final String[] lines = output.split("\n"); final String lastLine = lines[lines.length - 1]; final String hash = lastLine.split(" ")[1]; output = Execs.exec(bin + " name publish " + hash); if (StringUtils.isBlank(output) || !StringUtils.containsIgnoreCase(output, "published")) { LOGGER.log(Level.ERROR, "Executes [ipfs name publish] failed: " + output); return; } }
From source file:org.b3log.symphony.util.Markdowns.java
/** * Gets the safe HTML content of the specified content. * * @param content the specified content/* w w w. ja va 2 s . c om*/ * @param baseURI the specified base URI, the relative path value of href will starts with this URL * @return safe HTML content */ public static String clean(final String content, final String baseURI) { final Document.OutputSettings outputSettings = new Document.OutputSettings(); outputSettings.prettyPrint(false); final String tmp = Jsoup.clean(content, baseURI, Whitelist.relaxed().addAttributes(":all", "id", "target", "class") .addTags("span", "hr", "kbd", "samp", "tt", "del", "s", "strike", "u") .addAttributes("iframe", "src", "width", "height", "border", "marginwidth", "marginheight") .addAttributes("audio", "controls", "src") .addAttributes("video", "controls", "src", "width", "height") .addAttributes("source", "src", "media", "type") .addAttributes("object", "width", "height", "data", "type") .addAttributes("param", "name", "value") .addAttributes("input", "type", "disabled", "checked").addAttributes("embed", "src", "type", "width", "height", "wmode", "allowNetworking"), outputSettings); final Document doc = Jsoup.parse(tmp, baseURI, Parser.htmlParser()); final Elements ps = doc.getElementsByTag("p"); for (final Element p : ps) { p.removeAttr("style"); } final Elements iframes = doc.getElementsByTag("iframe"); for (final Element iframe : iframes) { final String src = StringUtils.deleteWhitespace(iframe.attr("src")); if (StringUtils.startsWithIgnoreCase(src, "javascript") || StringUtils.startsWithIgnoreCase(src, "data:")) { iframe.remove(); } } final Elements objs = doc.getElementsByTag("object"); for (final Element obj : objs) { final String data = StringUtils.deleteWhitespace(obj.attr("data")); if (StringUtils.startsWithIgnoreCase(data, "data:") || StringUtils.startsWithIgnoreCase(data, "javascript")) { obj.remove(); continue; } final String type = StringUtils.deleteWhitespace(obj.attr("type")); if (StringUtils.containsIgnoreCase(type, "script")) { obj.remove(); } } final Elements embeds = doc.getElementsByTag("embed"); for (final Element embed : embeds) { final String data = StringUtils.deleteWhitespace(embed.attr("src")); if (StringUtils.startsWithIgnoreCase(data, "data:") || StringUtils.startsWithIgnoreCase(data, "javascript")) { embed.remove(); continue; } } final Elements as = doc.getElementsByTag("a"); for (final Element a : as) { a.attr("rel", "nofollow"); final String href = a.attr("href"); if (href.startsWith(Latkes.getServePath())) { continue; } a.attr("target", "_blank"); } final Elements audios = doc.getElementsByTag("audio"); for (final Element audio : audios) { audio.attr("preload", "none"); } final Elements videos = doc.getElementsByTag("video"); for (final Element video : videos) { video.attr("preload", "none"); } String ret = doc.body().html(); ret = ret.replaceAll("(</?br\\s*/?>\\s*)+", "<br>"); // patch for Jsoup issue return ret; }
From source file:org.b3log.xiaov.service.QQService.java
private String answer(final String content, final String userName) { String keyword = ""; String[] keywords = StringUtils.split(XiaoVs.getString("bot.follow.keywords"), ","); keywords = Strings.trimAll(keywords); for (final String kw : keywords) { if (StringUtils.containsIgnoreCase(content, kw)) { keyword = kw;/*from w ww .j a va2s .c o m*/ break; } } String ret = ""; if (StringUtils.isNotBlank(keyword)) { try { ret = XiaoVs.getString("bot.follow.keywordAnswer"); ret = StringUtils.replace(ret, "{keyword}", URLEncoder.encode(keyword, "UTF-8")); } catch (final UnsupportedEncodingException e) { LOGGER.log(Level.ERROR, "Search key encoding failed", e); } } else if (StringUtils.contains(content, XiaoVs.QQ_BOT_NAME)) { if (1 == QQ_BOT_TYPE) { ret = turingQueryService.chat(userName, content); ret = StringUtils.replace(ret, "?", XiaoVs.QQ_BOT_NAME + ""); ret = StringUtils.replace(ret, "", XiaoVs.QQ_BOT_NAME + ""); ret = StringUtils.replace(ret, "<br>", "\n"); } else if (2 == QQ_BOT_TYPE) { ret = baiduQueryService.chat(content); } else if (3 == QQ_BOT_TYPE) { ret = itpkQueryService.chat(content); } if (StringUtils.isBlank(ret)) { ret = "~"; } } return ret; }