List of usage examples for org.apache.commons.lang StringUtils substringAfterLast
public static String substringAfterLast(String str, String separator)
Gets the substring after the last occurrence of a separator.
From source file:org.b3log.solo.processor.UserTemplateProcessor.java
/** * Shows the user template page.//from w ww. j ava 2 s . c o m * * @param context the specified context * @param request the specified HTTP servlet request * @param response the specified HTTP servlet response * @throws IOException io exception */ @RequestProcessing(value = "/*.html", method = HTTPRequestMethod.GET) public void showPage(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws IOException { final String requestURI = request.getRequestURI(); String templateName = StringUtils.substringAfterLast(requestURI, "/"); templateName = StringUtils.substringBefore(templateName, ".") + ".ftl"; LOGGER.log(Level.FINE, "Shows page[requestURI={0}, templateName={1}]", new Object[] { requestURI, templateName }); final AbstractFreeMarkerRenderer renderer = new FrontRenderer(); context.setRenderer(renderer); renderer.setTemplateName(templateName); final Map<String, Object> dataModel = renderer.getDataModel(); final Template template = Templates.getTemplate((String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), templateName); if (null == template) { try { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (final IOException ex) { LOGGER.severe(ex.getMessage()); } } try { final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request)); dataModel.putAll(langs); final JSONObject preference = preferenceQueryService.getPreference(); dataModel.put(Keys.PAGE_TYPE, PageTypes.USER_TEMPLATE); filler.fillBlogHeader(request, dataModel, preference); filler.fillUserTemplate(template, dataModel, preference); filler.fillBlogFooter(dataModel, preference); Skins.fillSkinLangs(preference.optString(Preference.LOCALE_STRING), (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), dataModel); request.setAttribute(PageCaches.CACHED_OID, "No id"); request.setAttribute(PageCaches.CACHED_TITLE, requestURI); request.setAttribute(PageCaches.CACHED_TYPE, langs.get(PageTypes.USER_TEMPLATE.getLangeLabel())); request.setAttribute(PageCaches.CACHED_LINK, requestURI); } catch (final Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); try { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (final IOException ex) { LOGGER.severe(ex.getMessage()); } } }
From source file:org.b3log.symphony.processor.AdminProcessor.java
/** * Shows admin point charge records./*from ww w . j a v a2s . co m*/ * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/admin/charge-records", method = HTTPRequestMethod.GET) @Before(adviceClass = { StopwatchStartAdvice.class, MallAdminCheck.class }) @After(adviceClass = { CSRFToken.class, StopwatchEndAdvice.class }) public void showChargeRecords(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(); context.setRenderer(renderer); renderer.setTemplateName("admin/charge-records.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); String pageNumStr = request.getParameter("p"); if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) { pageNumStr = "1"; } final int pageNum = Integer.valueOf(pageNumStr); final int pageSize = Symphonys.PAGE_SIZE; final JSONObject result = pointtransferQueryService.getChargeRecords(pageNum, pageSize); final List<JSONObject> results = (List<JSONObject>) result.opt(Keys.RESULTS); for (final JSONObject record : results) { final String toUserId = record.optString(Pointtransfer.TO_ID); final JSONObject toUser = userQueryService.getUser(toUserId); record.put(User.USER_NAME, toUser.optString(User.USER_NAME)); record.put(UserExt.USER_REAL_NAME, toUser.optString(UserExt.USER_REAL_NAME)); final String handlerId = StringUtils.substringAfterLast(record.optString(Pointtransfer.DATA_ID), "-"); final JSONObject handler = userQueryService.getUser(handlerId); record.put(Common.HANDLER_NAME, handler.optString(User.USER_NAME)); record.put(Common.HANDLER_REAL_NAME, handler.optString(UserExt.USER_REAL_NAME)); record.put(Pointtransfer.TIME, new Date(record.optLong(Pointtransfer.TIME))); record.put(Common.MONEY, StringUtils.substringBefore(record.optString(Pointtransfer.DATA_ID), "-")); } dataModel.put(Keys.RESULTS, results); final long chargePointSum = pointtransferQueryService.getChargePointSum(); final int pointExchangeUnit = Symphonys.getInt("pointExchangeUnit"); dataModel.put(Common.CHARGE_SUM, chargePointSum / pointExchangeUnit); final JSONObject pagination = result.optJSONObject(Pagination.PAGINATION); final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT); final JSONArray pageNums = pagination.optJSONArray(Pagination.PAGINATION_PAGE_NUMS); dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.opt(0)); dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.opt(pageNums.length() - 1)); dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum); dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); dataModel.put(Pagination.PAGINATION_PAGE_NUMS, CollectionUtils.jsonArrayToList(pageNums)); filler.fillHeaderAndFooter(request, response, dataModel); }
From source file:org.b3log.symphony.processor.FileUploadServlet.java
@Override public void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (QN_ENABLED) { return;// w w w . j a v a 2 s .c o m } final LatkeBeanManager beanManager = Lifecycle.getBeanManager(); final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class); final UserMgmtService userMgmtService = beanManager.getReference(UserMgmtService.class); try { if (null == userQueryService.getCurrentUser(req) && !userMgmtService.tryLogInWithCookie(req, resp)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } catch (final ServiceException e) { LOGGER.log(Level.ERROR, "Gets file failed", e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } final MultipartRequestInputStream multipartRequestInputStream = new MultipartRequestInputStream( req.getInputStream()); multipartRequestInputStream.readBoundary(); multipartRequestInputStream.readDataHeader("UTF-8"); final String mimeType = multipartRequestInputStream.getLastHeader().getContentType(); String suffix; String[] exts = MimeTypes.findExtensionsByMimeTypes(mimeType, false); if (null == exts || 0 == exts.length || exts.length > 1) { suffix = StringUtils.substringAfterLast(multipartRequestInputStream.getLastHeader().getFileName(), "."); } else { suffix = exts[0]; } final String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + 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); resp.setContentType("application/json"); final PrintWriter writer = resp.getWriter(); writer.append(data.toString()); writer.flush(); writer.close(); }
From source file:org.b3log.symphony.service.UserQueryService.java
/** * Gets user names from the specified text. * * <p>//w w w .ja v a2 s.co m * A user name is between @ and a punctuation, a blank or a line break (\n). For example, the specified text is * <pre>@88250 It is a nice day. @Vanessa, we are on the way.</pre> There are two user names in the text, * 88250 and Vanessa. * </p> * * @param text the specified text * @return user names, returns an empty set if not found * @throws ServiceException service exception */ public Set<String> getUserNames(final String text) throws ServiceException { final Set<String> ret = new HashSet<String>(); int idx = text.indexOf('@'); if (-1 == idx) { return ret; } String copy = text.trim(); copy = copy.replaceAll("\\n", " "); copy = copy.replaceAll("(?=\\pP)[^@]", " "); String[] uNames = StringUtils.substringsBetween(copy, "@", " "); String tail = StringUtils.substringAfterLast(copy, "@"); if (tail.contains(" ")) { tail = null; } if (null != tail) { if (null == uNames) { uNames = new String[1]; uNames[0] = tail; } else { uNames = Arrays.copyOf(uNames, uNames.length + 1); uNames[uNames.length - 1] = tail; } } if (null == uNames) { return ret; } for (int i = 0; i < uNames.length; i++) { final String maybeUserName = uNames[i]; if (!UserRegisterValidation.invalidUserName(maybeUserName)) { // A string match the user name pattern if (null != getUserByName(maybeUserName)) { // Found a user ret.add(maybeUserName); copy = copy.replaceFirst("@" + maybeUserName, ""); idx = copy.indexOf('@'); if (-1 == idx) { return ret; } } } } return ret; }
From source file:org.beanfuse.archiver.ZipUtils.java
public static File zip(List fileNames, String zipPath, String encoding) { try {/*w w w . j a va2 s. c om*/ FileOutputStream f = new FileOutputStream(zipPath); ZipOutputStream out = new ZipOutputStream(new DataOutputStream(f)); out.setEncoding(encoding); for (int i = 0; i < fileNames.size(); i++) { DataInputStream in = new DataInputStream(new FileInputStream(fileNames.get(i).toString())); out.putNextEntry(new org.apache.tools.zip.ZipEntry( StringUtils.substringAfterLast(fileNames.get(i).toString(), File.separator))); int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); } out.close(); return new File(zipPath); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.beanfuse.model.EntityUtils.java
public static String getCommandName(String entityName) { return StringUtils.uncapitalize(StringUtils.substringAfterLast(entityName, ".")); }
From source file:org.beanfuse.utils.web.DownloadHelper.java
public static void download(HttpServletRequest request, HttpServletResponse response, InputStream inStream, String name, String display) { String attch_name = ""; byte[] b = new byte[1024]; int len = 0;/*from ww w.j a va 2s.c om*/ try { String ext = StringUtils.substringAfterLast(name, "."); if (StringUtils.isBlank(display)) { attch_name = getAttachName(name); } else { attch_name = display; if (!attch_name.endsWith("." + ext)) { attch_name += "." + ext; } } response.reset(); String contentType = response.getContentType(); if (null == contentType) { if (StringUtils.isEmpty(ext)) { contentType = "application/x-msdownload"; } else { contentType = contentTypes.getProperty(ext, "application/x-msdownload"); } response.setContentType(contentType); logger.debug("set content type {} for {}", contentType, attch_name); } response.addHeader("Content-Disposition", "attachment; filename=\"" + encodeAttachName(request, attch_name) + "\""); while ((len = inStream.read(b)) > 0) { response.getOutputStream().write(b, 0, len); } inStream.close(); } catch (Exception e) { logger.warn("download file error=" + attch_name, e); } }
From source file:org.beangle.commons.archiver.ZipUtils.java
public static File zip(List<String> fileNames, String zipPath, String encoding) { try {//from w w w .j a va2 s.c o m FileOutputStream f = new FileOutputStream(zipPath); ZipArchiveOutputStream zos = (ZipArchiveOutputStream) new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.ZIP, f); if (null != encoding) { zos.setEncoding(encoding); } for (int i = 0; i < fileNames.size(); i++) { String fileName = fileNames.get(i); String entryName = StringUtils.substringAfterLast(fileName, File.separator); ZipArchiveEntry entry = new ZipArchiveEntry(entryName); zos.putArchiveEntry(entry); FileInputStream fis = new FileInputStream(fileName); IOUtils.copy(fis, zos); fis.close(); zos.closeArchiveEntry(); } zos.close(); return new File(zipPath); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.beangle.commons.text.replacer.BatchReplaceMain.java
public static void replaceFile(String fileName, final Map<String, List<Replacer>> profiles, String encoding) throws Exception, FileNotFoundException { File file = new File(fileName); if (file.isFile() && !file.isHidden()) { List<Replacer> replacers = profiles.get(StringUtils.substringAfterLast(fileName, ".")); if (null == replacers) { return; }//from ww w . ja v a2 s . co m logger.info("processing {}", fileName); String filecontent = FileUtils.readFileToString(file, encoding); filecontent = Replacer.process(filecontent, replacers); writeToFile(filecontent, fileName, encoding); } else { String[] subFiles = file.list(new FilenameFilter() { public boolean accept(File dir, String name) { if (dir.isDirectory()) return true; boolean matched = false; for (String key : profiles.keySet()) { matched = name.endsWith(key); if (matched) return true; } return false; } }); if (null != subFiles) { for (int i = 0; i < subFiles.length; i++) { replaceFile(fileName + '/' + subFiles[i], profiles, encoding); } } } }
From source file:org.beangle.ems.avatar.model.FileAvatar.java
public String getType() { if (null == super.getType()) { setType(StringUtils.substringAfterLast(file.getAbsolutePath(), ".")); }// w w w. j a va 2 s . c o m return super.getType(); }