List of usage examples for org.apache.commons.lang StringUtils substringBeforeLast
public static String substringBeforeLast(String str, String separator)
Gets the substring before the last occurrence of a separator.
From source file:org.b3log.solo.processor.FileUploadProcessor.java
@Override public void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (QN_ENABLED) { return;/*ww w. j a v a2s . com*/ } final MultipartRequestInputStream multipartRequestInputStream = new MultipartRequestInputStream( req.getInputStream()); multipartRequestInputStream.readBoundary(); multipartRequestInputStream.readDataHeader("UTF-8"); String fileName = multipartRequestInputStream.getLastHeader().getFileName(); String suffix = StringUtils.substringAfterLast(fileName, "."); if (StringUtils.isBlank(suffix)) { final String mimeType = multipartRequestInputStream.getLastHeader().getContentType(); String[] exts = MimeTypes.findExtensionsByMimeTypes(mimeType, false); if (null != exts && 0 < exts.length) { suffix = exts[0]; } else { suffix = StringUtils.substringAfter(mimeType, "/"); } } final String name = StringUtils.substringBeforeLast(fileName, "."); final String processName = name.replaceAll("\\W", ""); final String uuid = UUID.randomUUID().toString().replaceAll("-", ""); if (StringUtils.isBlank(processName)) { fileName = uuid + "." + suffix; } else { fileName = uuid + '_' + processName + "." + suffix; } final OutputStream output = new FileOutputStream(UPLOAD_DIR + fileName); IOUtils.copy(multipartRequestInputStream, output); IOUtils.closeQuietly(multipartRequestInputStream); IOUtils.closeQuietly(output); final JSONObject data = new JSONObject(); data.put("key", Latkes.getServePath() + "/upload/" + fileName); data.put("name", fileName); resp.setContentType("application/json"); final PrintWriter writer = resp.getWriter(); writer.append(data.toString()); writer.flush(); writer.close(); }
From source file:org.b3log.solo.service.ImportService.java
private JSONObject parseArticle(final String fileName, String fileContent) { fileContent = StringUtils.trim(fileContent); String frontMatter = StringUtils.substringBefore(fileContent, "---"); if (StringUtils.isBlank(frontMatter)) { fileContent = StringUtils.substringAfter(fileContent, "---"); frontMatter = StringUtils.substringBefore(fileContent, "---"); }/* w w w. ja v a 2 s .co m*/ final JSONObject ret = new JSONObject(); final Yaml yaml = new Yaml(); Map elems; try { elems = (Map) yaml.load(frontMatter); } catch (final Exception e) { // treat it as plain markdown ret.put(Article.ARTICLE_TITLE, StringUtils.substringBeforeLast(fileName, ".")); ret.put(Article.ARTICLE_CONTENT, fileContent); ret.put(Article.ARTICLE_ABSTRACT, Article.getAbstract(fileContent)); ret.put(Article.ARTICLE_TAGS_REF, DEFAULT_TAG); ret.put(Article.ARTICLE_IS_PUBLISHED, true); ret.put(Article.ARTICLE_COMMENTABLE, true); ret.put(Article.ARTICLE_VIEW_PWD, ""); return ret; } String title = (String) elems.get("title"); if (StringUtils.isBlank(title)) { title = StringUtils.substringBeforeLast(fileName, "."); } ret.put(Article.ARTICLE_TITLE, title); String content = StringUtils.substringAfter(fileContent, frontMatter); if (StringUtils.startsWith(content, "---")) { content = StringUtils.substringAfter(content, "---"); content = StringUtils.trim(content); } ret.put(Article.ARTICLE_CONTENT, content); final String abs = parseAbstract(elems, content); ret.put(Article.ARTICLE_ABSTRACT, abs); final Date date = parseDate(elems); ret.put(Article.ARTICLE_CREATED, date.getTime()); final String permalink = (String) elems.get("permalink"); if (StringUtils.isNotBlank(permalink)) { ret.put(Article.ARTICLE_PERMALINK, permalink); } final List<String> tags = parseTags(elems); final StringBuilder tagBuilder = new StringBuilder(); for (final String tag : tags) { tagBuilder.append(tag).append(","); } tagBuilder.deleteCharAt(tagBuilder.length() - 1); ret.put(Article.ARTICLE_TAGS_REF, tagBuilder.toString()); ret.put(Article.ARTICLE_IS_PUBLISHED, true); ret.put(Article.ARTICLE_COMMENTABLE, true); ret.put(Article.ARTICLE_VIEW_PWD, ""); return ret; }
From source file:org.b3log.solo.util.Solos.java
/** * Gets the current logged-in user./*from w ww.j a va 2s. co m*/ * * @param request the specified request * @param response the specified response * @return the current logged-in user, returns {@code null} if not found */ public static JSONObject getCurrentUser(final HttpServletRequest request, final HttpServletResponse response) { final Cookie[] cookies = request.getCookies(); if (null == cookies || 0 == cookies.length) { return null; } final BeanManager beanManager = BeanManager.getInstance(); final UserRepository userRepository = beanManager.getReference(UserRepository.class); try { for (int i = 0; i < cookies.length; i++) { final Cookie cookie = cookies[i]; if (!COOKIE_NAME.equals(cookie.getName())) { continue; } final String value = Crypts.decryptByAES(cookie.getValue(), COOKIE_SECRET); final JSONObject cookieJSONObject = new JSONObject(value); final String userId = cookieJSONObject.optString(Keys.OBJECT_ID); if (StringUtils.isBlank(userId)) { break; } JSONObject user = userRepository.get(userId); if (null == user) { break; } final String userPassword = user.optString(User.USER_PASSWORD); final String token = cookieJSONObject.optString(Keys.TOKEN); final String hashPassword = StringUtils.substringBeforeLast(token, ":"); if (userPassword.equals(hashPassword)) { login(user, response); return user; } } } catch (final Exception e) { LOGGER.log(Level.TRACE, "Parses cookie failed, clears the cookie [name=" + COOKIE_NAME + "]"); final Cookie cookie = new Cookie(COOKIE_NAME, null); cookie.setMaxAge(0); cookie.setPath("/"); response.addCookie(cookie); } return null; }
From source file:org.b3log.symphony.processor.FileUploadServlet.java
@Override public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (QN_ENABLED) { return;//from w w w . j a v a2 s. com } final LatkeBeanManager beanManager = Lifecycle.getBeanManager(); final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class); final UserMgmtService userMgmtService = beanManager.getReference(UserMgmtService.class); final OptionQueryService optionQueryService = beanManager.getReference(OptionQueryService.class); try { final JSONObject option = optionQueryService.getOption(Option.ID_C_MISC_ALLOW_ANONYMOUS_VIEW); if (!"0".equals(option.optString(Option.OPTION_VALUE))) { if (null == userQueryService.getCurrentUser(req) && !userMgmtService.tryLogInWithCookie(req, resp)) { final String referer = req.getHeader("Referer"); if (!StringUtils.contains(referer, "fangstar.net")) { final String authorization = req.getHeader("Authorization"); LOGGER.debug("Referer [" + referer + "], Authorization [" + authorization + "]"); if (!StringUtils.contains(authorization, "Basic ")) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } else { String usernamePwd = StringUtils.substringAfter(authorization, "Basic "); usernamePwd = Base64.decodeToString(usernamePwd); final String username = usernamePwd.split(":")[0]; final String password = usernamePwd.split(":")[1]; if (!StringUtils.equals(username, Symphonys.get("http.basic.auth.username")) || !StringUtils.equals(password, Symphonys.get("http.basic.auth.password"))) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } } } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets file failed", e); resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } final String uri = req.getRequestURI(); String key = uri.substring("/upload/".length()); key = StringUtils.substringBeforeLast(key, "-64.jpg"); // Erase Qiniu template key = StringUtils.substringBeforeLast(key, "-260.jpg"); // Erase Qiniu template String path = UPLOAD_DIR + key; if (!FileUtil.isExistingFile(new File(path))) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final byte[] data = IOUtils.toByteArray(new FileInputStream(path)); final String ifNoneMatch = req.getHeader("If-None-Match"); final String etag = "\"" + MD5.hash(new String(data)) + "\""; resp.addHeader("Cache-Control", "public, max-age=31536000"); resp.addHeader("ETag", etag); resp.setHeader("Server", "Latke Static Server (v" + SymphonyServletListener.VERSION + ")"); if (etag.equals(ifNoneMatch)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } final OutputStream output = resp.getOutputStream(); IOUtils.write(data, output); output.flush(); IOUtils.closeQuietly(output); }
From source file:org.b3log.symphony.service.AvatarQueryService.java
/** * Fills the specified user thumbnail URL. * * @param user the specified user/*ww w .j av a2 s. co m*/ */ public void fillUserAvatarURL(final JSONObject user) { final String originalURL = user.optString(UserExt.USER_AVATAR_URL); if (Symphonys.getBoolean("qiniu.enabled")) { if (!StringUtils.contains(originalURL, "qnssl.com") && !StringUtils.contains(originalURL, "clouddn.com")) { user.put(UserExt.USER_AVATAR_URL, DEFAULT_AVATAR_URL); return; } } user.put(UserExt.USER_AVATAR_URL, StringUtils.substringBeforeLast(originalURL, "?")); }
From source file:org.b3log.symphony.service.AvatarQueryService.java
/** * Gets the avatar URL for the specified user id with the specified size. * * @param user the specified user//from w w w. ja v a2 s . c o m * @return the avatar URL */ public String getAvatarURLByUser(final JSONObject user) { if (null == user) { return DEFAULT_AVATAR_URL; } final String originalURL = user.optString(UserExt.USER_AVATAR_URL); if (StringUtils.isBlank(originalURL)) { return DEFAULT_AVATAR_URL; } if (Symphonys.getBoolean("qiniu.enabled")) { if (!StringUtils.contains(originalURL, "qnssl.com") && !StringUtils.contains(originalURL, "clouddn.com")) { return DEFAULT_AVATAR_URL; } } return StringUtils.substringBeforeLast(originalURL, "?"); }
From source file:org.b3log.symphony.service.ManQueryService.java
/** * Initializes manuals./* ww w . jav a2 s. c o m*/ */ private static void init() { // http://stackoverflow.com/questions/585534/what-is-the-best-way-to-find-the-users-home-directory-in-java final String userHome = System.getProperty("user.home"); if (StringUtils.isBlank(userHome)) { return; } try { Thread.sleep(5 * 1000); final String tldrPagesPath = userHome + File.separator + "tldr" + File.separator + "pages" + File.separator; final Collection<File> mans = FileUtils.listFiles(new File(tldrPagesPath), new String[] { "md" }, true); for (final File manFile : mans) { InputStream is = null; try { is = new FileInputStream(manFile); final String md = IOUtils.toString(is, "UTF-8"); String html = Markdowns.toHTML(md); final JSONObject cmdMan = new JSONObject(); cmdMan.put(Common.MAN_CMD, StringUtils.substringBeforeLast(manFile.getName(), ".")); html = html.replace("\n", "").replace("\r", ""); cmdMan.put(Common.MAN_HTML, html); CMD_MANS.add(cmdMan); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Loads man [" + manFile.getPath() + "] failed", e); } finally { IOUtils.closeQuietly(is); } } } catch (final Exception e) { return; } TLDR_ENABLED = !CMD_MANS.isEmpty(); Collections.sort(CMD_MANS, (o1, o2) -> { final String c1 = o1.optString(Common.MAN_CMD); final String c2 = o2.optString(Common.MAN_CMD); return c1.compareToIgnoreCase(c2); }); }
From source file:org.b3log.symphony.util.Links.java
/** * Gets links from the specified HTML./*from ww w.ja va 2s . com*/ * * @param baseURL the specified base URL * @param html the specified HTML * @return a list of links, each of them like this: <pre> * { * "linkAddr": "https://hacpai.com/article/1440573175609", * "linkTitle": "", * "linkKeywords": "", * "linkHTML": "page HTML", * "linkText": "page text", * "linkBaiduRefCnt": int * } * </pre> */ public static List<JSONObject> getLinks(final String baseURL, final String html) { final Document doc = Jsoup.parse(html, baseURL); final Elements urlElements = doc.select("a"); final Set<String> urls = new HashSet<>(); final List<Spider> spiders = new ArrayList<>(); String url = null; for (final Element urlEle : urlElements) { try { url = urlEle.absUrl("href"); if (StringUtils.isBlank(url) || !StringUtils.contains(url, "://")) { url = StringUtils.substringBeforeLast(baseURL, "/") + url; } final URL formedURL = new URL(url); final String protocol = formedURL.getProtocol(); final String host = formedURL.getHost(); final int port = formedURL.getPort(); final String path = formedURL.getPath(); url = protocol + "://" + host; if (-1 != port && 80 != port && 443 != port) { url += ":" + port; } url += path; if (StringUtils.endsWith(url, "/")) { url = StringUtils.substringBeforeLast(url, "/"); } urls.add(url); } catch (final Exception e) { LOGGER.warn("Can't parse [" + url + "]"); } } final List<JSONObject> ret = new ArrayList<>(); try { for (final String u : urls) { spiders.add(new Spider(u)); } final List<Future<JSONObject>> results = Symphonys.EXECUTOR_SERVICE.invokeAll(spiders); for (final Future<JSONObject> result : results) { final JSONObject link = result.get(); if (null == link) { continue; } ret.add(link); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Parses URLs failed", e); } Collections.sort(ret, new Comparator<JSONObject>() { @Override public int compare(final JSONObject link1, final JSONObject link2) { return link1.optInt(Link.LINK_BAIDU_REF_CNT) - link2.optInt(Link.LINK_BAIDU_REF_CNT); } }); return ret; }
From source file:org.beangle.model.entity.populator.ConvertPopulatorBean.java
/** * ???/*from w w w. j a va2s .c o m*/ * * @param target * @param attr * @param value */ public void populateValue(final Object target, String entityName, final String attr, Object value) { try { if (attr.indexOf('.') > -1) { initProperty(target, entityName, StringUtils.substringBeforeLast(attr, ".")); } // BugDate?? if (value instanceof Date) { Date date = (Date) value; value = sdf.format(date); } // ??? if ("".equals(value) || "?".equals(value)) { Class type = beanUtils.getPropertyUtils().getPropertyDescriptor(target, attr).getPropertyType(); if (Boolean.class.equals(type) || "boolean".equals(type.getName())) { if ("".equals(value)) { value = "1"; } else { value = "0"; } } } beanUtils.copyProperty(target, attr, value); } catch (Exception e) { logger.error("copy property failure:[class:" + entityName + " attr:" + attr + " value:" + value + "]:", e); } }
From source file:org.beangle.model.persist.hibernate.support.DefaultTableNameConfig.java
public String classToTableName(String className) { if (className.endsWith("Bean")) { className = StringUtils.substringBeforeLast(className, "Bean"); }// www . j av a2 s. com String tableName = addUnderscores(unqualify(className)); if (enablePluralize) { tableName = pluralizer.pluralize(tableName); } TableNamePattern pattern = getPattern(className); if (null != pattern) { tableName = pattern.prefix + tableName; } if (tableName.length() > MaxLength && null != pattern) { for (Map.Entry<String, String> pairEntry : pattern.abbreviations.entrySet()) { tableName = StringUtils.replace(tableName, pairEntry.getKey(), pairEntry.getValue()); } } return tableName; }