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.apache.jetspeed.portlets.spaces.SpaceNavigator.java
@SuppressWarnings("unchecked") protected static SpaceChangeContext changeSpace(RenderRequest request, Spaces spacesService, String spaceName) throws PortletException { String userName = (request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : null); UserSpaceBeanList spaces = (UserSpaceBeanList) request.getPortletSession() .getAttribute(SpaceNavigator.ATTRIBUTE_SPACES, PortletSession.APPLICATION_SCOPE); // Validating the spaces cache in session if it was for the same user if (spaces != null && !StringUtils.equals(spaces.getUserName(), userName)) { request.getPortletSession().removeAttribute(SpaceNavigator.ATTRIBUTE_SPACES, PortletSession.APPLICATION_SCOPE); spaces = null;/* w ww .ja v a 2 s. com*/ } if (spaces == null) { // TODO: use environment spaces = createSpaceBeanList(spacesService, userName, null); if (request.getUserPrincipal() != null) { String username = request.getUserPrincipal().getName(); Space home = spacesService.lookupUserSpace(username); if (home != null) { if (home.getOwner() == null) { try { home.setOwner(username); spacesService.storeSpace(home); } catch (SpacesException e) { throw new PortletException(e); } } SpaceBean userHome = new SpaceBean(home); userHome.setDescription(home.getDescription()); userHome.setTitle(home.getTitle()); userHome.setUserHomePath(home.getPath()); userHome.setUserHomeName(home.getName()); spaces.add(userHome); } } request.getPortletSession().setAttribute(SpaceNavigator.ATTRIBUTE_SPACES, spaces, PortletSession.APPLICATION_SCOPE); } boolean changed = false; SpaceBean space = (SpaceBean) request.getPortletSession().getAttribute(SpaceNavigator.ATTRIBUTE_SPACE, PortletSession.APPLICATION_SCOPE); if (space == null && spaceName != null) { space = findSpaceByName(spaces, spaceName); changed = (space != null); } // check if this space matches the current portal page path. RequestContext rc = (RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV); String portalPagePath = rc.getPage().getPath(); String portalPageFolderPath = StringUtils.substringBeforeLast(portalPagePath, Folder.PATH_SEPARATOR); boolean isRootSpace = StringUtils.isEmpty(portalPageFolderPath); if (isRootSpace) { for (SpaceBean spaceBean : spaces) { if (Folder.PATH_SEPARATOR.equals(spaceBean.getPath())) { if (!spaceBean.equals(space)) { space = spaceBean; changed = true; } break; } } } else { for (SpaceBean spaceBean : spaces) { if (Folder.PATH_SEPARATOR.equals(spaceBean.getPath())) { continue; } if (portalPageFolderPath.equals(spaceBean.getPath()) || portalPageFolderPath.startsWith(spaceBean.getPath() + "/")) { if (!spaceBean.equals(space)) { space = spaceBean; changed = true; } break; } } } if (space == null && !spaces.isEmpty()) { space = spaces.get(0); changed = true; } if (changed) { request.getPortletSession().setAttribute(SpaceNavigator.ATTRIBUTE_SPACE, space, PortletSession.APPLICATION_SCOPE); } return new SpaceChangeContext(space, spaces); }
From source file:org.apache.maven.scm.provider.svn.svnexe.command.remoteinfo.SvnRemoteInfoCommand.java
@Override public RemoteInfoScmResult executeRemoteInfoCommand(ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters) throws ScmException { String url = ((SvnScmProviderRepository) repository).getUrl(); // use a default svn layout, url is here http://svn.apache.org/repos/asf/maven/maven-3/trunk // so as we presume we have good users using standard svn layout, we calculate tags and branches url String baseUrl = StringUtils.endsWith(url, "/") ? StringUtils.substringAfter(StringUtils.removeEnd(url, "/"), "/") : StringUtils.substringBeforeLast(url, "/"); Commandline cl = SvnCommandLineUtils.getBaseSvnCommandLine(fileSet == null ? null : fileSet.getBasedir(), (SvnScmProviderRepository) repository); cl.createArg().setValue("ls"); cl.createArg().setValue(baseUrl + "/tags"); CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer(); LsConsumer consumer = new LsConsumer(getLogger(), baseUrl); int exitCode = 0; Map<String, String> tagsInfos = null; try {/*from ww w . java 2s . c o m*/ exitCode = SvnCommandLineUtils.execute(cl, consumer, stderr, getLogger()); tagsInfos = consumer.infos; } catch (CommandLineException ex) { throw new ScmException("Error while executing svn command.", ex); } if (exitCode != 0) { return new RemoteInfoScmResult(cl.toString(), "The svn command failed.", stderr.getOutput(), false); } cl = SvnCommandLineUtils.getBaseSvnCommandLine(fileSet == null ? null : fileSet.getBasedir(), (SvnScmProviderRepository) repository); cl.createArg().setValue("ls"); cl.createArg().setValue(baseUrl + "/tags"); stderr = new CommandLineUtils.StringStreamConsumer(); consumer = new LsConsumer(getLogger(), baseUrl); Map<String, String> branchesInfos = null; try { exitCode = SvnCommandLineUtils.execute(cl, consumer, stderr, getLogger()); branchesInfos = consumer.infos; } catch (CommandLineException ex) { throw new ScmException("Error while executing svn command.", ex); } if (exitCode != 0) { return new RemoteInfoScmResult(cl.toString(), "The svn command failed.", stderr.getOutput(), false); } return new RemoteInfoScmResult(cl.toString(), branchesInfos, tagsInfos); }
From source file:org.apache.maven.scm.provider.svn.svnjava.command.remoteinfo.SvnJavaRemoteInfoCommand.java
@Override public RemoteInfoScmResult executeRemoteInfoCommand(ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters) throws ScmException { SvnJavaScmProviderRepository javaRepo = (SvnJavaScmProviderRepository) repository; String url = ((SvnScmProviderRepository) repository).getUrl(); // use a default svn layout, url is here http://svn.apache.org/repos/asf/maven/maven-3/trunk // so as we presume we have good users using standard svn layout, we calculate tags and branches url String baseUrl = StringUtils.endsWith(url, "/") ? StringUtils.substringAfter(StringUtils.removeEnd(url, "/"), "/") : StringUtils.substringBeforeLast(url, "/"); RemoteInfoScmResult remoteInfoScmResult = new RemoteInfoScmResult(null, null, null, true); try {//ww w . j av a 2 s . c om DirEntryHandler dirEntryHandler = new DirEntryHandler(baseUrl); javaRepo.getClientManager().getLogClient().doList(SVNURL.parseURIEncoded(baseUrl + "/tags"), SVNRevision.HEAD, SVNRevision.HEAD, false, false, dirEntryHandler); remoteInfoScmResult.setTags(dirEntryHandler.infos); } catch (SVNException e) { return new RemoteInfoScmResult(null, e.getMessage(), null, false); } try { DirEntryHandler dirEntryHandler = new DirEntryHandler(baseUrl); javaRepo.getClientManager().getLogClient().doList(SVNURL.parseURIEncoded(baseUrl + "/branches"), SVNRevision.HEAD, SVNRevision.HEAD, false, false, dirEntryHandler); remoteInfoScmResult.setBranches(dirEntryHandler.infos); } catch (SVNException e) { return new RemoteInfoScmResult(null, e.getMessage(), null, false); } return remoteInfoScmResult; }
From source file:org.apache.myfaces.custom.tree2.TreeWalkerBase.java
public boolean next() { if (!startedWalking) { // the first next() call just needs to set the root node and push it onto the stack idStack.push(ROOT_NODE_ID);//from ww w. j av a2 s .c om tree.setNodeId(ROOT_NODE_ID); nodeStack.push(tree.getNode()); startedWalking = true; return true; } if (nodeStack.isEmpty()) { return false; } TreeNode prevNode = (TreeNode) nodeStack.peek(); String prevNodeId = (String) idStack.peek(); if (prevNode.isLeaf()) { nodeStack.pop(); idStack.pop(); return next(); } else { TreeNode nextNode = null; String nextNodeId = null; if (prevNodeId.equals(tree.getNodeId())) { /** * We know there is at least one child b/c otherwise we would have popped the node after * checking isLeaf. Basically we need to keep drilling down until we reach the deepest * node that is available for "walking." Then we'll return to the parent and render its * siblings and walk back up the tree. */ nextNodeId = prevNodeId + TREE_NODE_SEPARATOR + "0"; // don't render any children if the node is not expanded if (checkState) { if (!tree.getDataModel().getTreeState().isNodeExpanded(prevNodeId)) { nodeStack.pop(); idStack.pop(); return next(); } } } else { // get the parent node String currentNodeId = tree.getNodeId(); String parentNodeId = StringUtils.substringBeforeLast(currentNodeId, TREE_NODE_SEPARATOR); tree.setNodeId(parentNodeId); TreeNode parentNode = tree.getNode(); int siblingCount = Integer.parseInt(currentNodeId.substring(parentNodeId.length() + 1)); siblingCount++; if (siblingCount == parentNode.getChildCount()) { // no more siblings nodeStack.pop(); idStack.pop(); return next(); } nextNodeId = parentNodeId + TREE_NODE_SEPARATOR + siblingCount; } tree.setNodeId(nextNodeId); nextNode = tree.getNode(); nodeStack.push(nextNode); idStack.push(nextNodeId); return true; } }
From source file:org.apache.sling.hc.core.impl.servlet.HealthCheckExecutorServlet.java
@Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { String tagsStr = StringUtils.defaultIfEmpty(StringUtils.substringBeforeLast(request.getPathInfo(), "."), "") .replace("/", ""); if (StringUtils.isBlank(tagsStr)) { // if not provided via path use parameter or default tagsStr = StringUtils.defaultIfEmpty(request.getParameter(PARAM_TAGS.name), ""); }/* w w w. ja v a 2 s. c om*/ final String[] tags = tagsStr.split("[, ;]+"); String format = StringUtils.substringAfterLast(request.getPathInfo(), "."); if (StringUtils.isBlank(format)) { // if not provided via extension use parameter or default format = StringUtils.defaultIfEmpty(request.getParameter(PARAM_FORMAT.name), FORMAT_HTML); } final Boolean includeDebug = Boolean.valueOf(request.getParameter(PARAM_INCLUDE_DEBUG.name)); final Map<Result.Status, Integer> statusMapping = request.getParameter(PARAM_HTTP_STATUS.name) != null ? getStatusMapping(request.getParameter(PARAM_HTTP_STATUS.name)) : null; HealthCheckExecutionOptions options = new HealthCheckExecutionOptions(); options.setCombineTagsWithOr(Boolean .valueOf(StringUtils.defaultString(request.getParameter(PARAM_COMBINE_TAGS_WITH_OR.name), "true"))); options.setForceInstantExecution(Boolean.valueOf(request.getParameter(PARAM_FORCE_INSTANT_EXECUTION.name))); String overrideGlobalTimeoutVal = request.getParameter(PARAM_OVERRIDE_GLOBAL_TIMEOUT.name); if (StringUtils.isNumeric(overrideGlobalTimeoutVal)) { options.setOverrideGlobalTimeout(Integer.valueOf(overrideGlobalTimeoutVal)); } List<HealthCheckExecutionResult> executionResults = this.healthCheckExecutor.execute(options, tags); Result.Status mostSevereStatus = Result.Status.DEBUG; for (HealthCheckExecutionResult executionResult : executionResults) { Status status = executionResult.getHealthCheckResult().getStatus(); if (status.ordinal() > mostSevereStatus.ordinal()) { mostSevereStatus = status; } } Result overallResult = new Result(mostSevereStatus, "Overall status " + mostSevereStatus); sendNoCacheHeaders(response); if (statusMapping != null) { Integer httpStatus = statusMapping.get(overallResult.getStatus()); response.setStatus(httpStatus); } if (FORMAT_HTML.equals(format)) { sendHtmlResponse(overallResult, executionResults, request, response, includeDebug); } else if (FORMAT_JSON.equals(format)) { sendJsonResponse(overallResult, executionResults, null, response, includeDebug); } else if (FORMAT_JSONP.equals(format)) { String jsonpCallback = StringUtils.defaultIfEmpty(request.getParameter(PARAM_JSONP_CALLBACK.name), JSONP_CALLBACK_DEFAULT); sendJsonResponse(overallResult, executionResults, jsonpCallback, response, includeDebug); } else if (FORMAT_TXT.equals(format)) { sendTxtResponse(overallResult, response); } else { response.setContentType("text/plain"); response.getWriter().println("Invalid format " + format + " - supported formats: html|json|jsonp|txt"); } }
From source file:org.apache.sling.slingoakrestrictions.impl.ResourceTypePatternTest.java
@Before public void setup() { initMocks(this); setupTreeMock(testTreeParentOutsideScope, StringUtils.substringBeforeLast(TEST_PATH, "/"), null, RESOURCE_TYPE_OUTSIDE_SCOPE); setupTreeMock(testTree, StringUtils.substringAfterLast(TEST_PATH, "/"), testTreeParentOutsideScope, RESOURCE_TYPE_TEST_PATH);// w w w . jav a 2 s . c o m setupTreeMock(testTreeSub1, TEST_NODE_SUB1, testTree, RESOURCE_TYPE_SUB1); setupTreeMock(testTreeSub2, TEST_NODE_SUB2, testTree, RESOURCE_TYPE_SUB2); setupTreeMock(testTreeSub3, TEST_NODE_SUB3, testTree, RESOURCE_TYPE_SUB3); setupTreeMock(testTreeSub3Sub1, TEST_NODE_SUBSUB1, testTreeSub3, RESOURCE_TYPE_SUBSUB1); setupTreeMock(testTreeSub3Sub2, TEST_NODE_SUBSUB2, testTreeSub3, RESOURCE_TYPE_SUBSUB1); }
From source file:org.astore.core.batch.task.BatchIntegrationTest.java
@Before public void setUp() throws Exception { random = new Random(); mediaHeader = batchMediaConverter.getHeader(); productId = Long.valueOf(Math.abs((long) random.nextInt())); sequenceId = Long.valueOf(Math.abs((long) random.nextInt())); importCsv("/astorecore/test/testBatch.impex", "utf-8"); // don't import binary data -> temporarily remove MediaTranslator ((DefaultImpexConverter) batchMediaConverter).setHeader(StringUtils.substringBeforeLast(mediaHeader, ";")); }
From source file:org.b3log.latke.plugin.PluginManager.java
/** * Loads a plugin by the specified plugin directory and put it into the * specified holder./*from w w w .ja va 2s . c o m*/ * * @param pluginDir the specified plugin directory * @param holder the specified holder * @return loaded plugin * @throws Exception exception */ private AbstractPlugin load(final File pluginDir, final HashMap<String, HashSet<AbstractPlugin>> holder) throws Exception { final Properties props = new Properties(); props.load(new FileInputStream(pluginDir.getPath() + File.separator + "plugin.properties")); final File defaultClassesFileDir = new File(pluginDir.getPath() + File.separator + "classes"); final URL defaultClassesFileDirURL = defaultClassesFileDir.toURI().toURL(); final String webRoot = StringUtils.substringBeforeLast(AbstractServletListener.getWebRoot(), File.separator); final String classesFileDirPath = webRoot + props.getProperty("classesDirPath"); final File classesFileDir = new File(classesFileDirPath); final URL classesFileDirURL = classesFileDir.toURI().toURL(); final URLClassLoader classLoader = new URLClassLoader( new URL[] { defaultClassesFileDirURL, classesFileDirURL }, PluginManager.class.getClassLoader()); classLoaders.add(classLoader); String pluginClassName = props.getProperty(Plugin.PLUGIN_CLASS); if (StringUtils.isBlank(pluginClassName)) { pluginClassName = NotInteractivePlugin.class.getName(); } final String rendererId = props.getProperty(Plugin.PLUGIN_RENDERER_ID); if (StringUtils.isBlank(rendererId)) { LOGGER.log(Level.WARNING, "no renderer defined by this plugin[" + pluginDir.getName() + "]this plugin will be ignore!"); return null; } final Class<?> pluginClass = classLoader.loadClass(pluginClassName); LOGGER.log(Level.FINEST, "Loading plugin class[name={0}]", pluginClassName); final AbstractPlugin ret = (AbstractPlugin) pluginClass.newInstance(); ret.setRendererId(rendererId); setPluginProps(pluginDir, ret, props); registerEventListeners(props, classLoader, ret); register(ret, holder); ret.changeStatus(); return ret; }
From source file:org.b3log.solo.processor.ArticleProcessor.java
/** * Gets the request archive from the specified request URI. * /*from ww w . jav a2 s.co m*/ * @param requestURI the specified request URI * @return archive, for example "2012/05" */ private static String getArchivesArticlesPagedArchive(final String requestURI) { String archiveAndPageNum = requestURI.substring((Latkes.getContextPath() + "/articles/archives/").length()); if (!archiveAndPageNum.endsWith("/")) { archiveAndPageNum += "/"; } return StringUtils.substringBeforeLast(archiveAndPageNum, "/"); }
From source file:org.b3log.solo.processor.FileUploadProcessor.java
@Override public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (QN_ENABLED) { return;//from w w w . j a va2s . c o m } final String uri = req.getRequestURI(); String key = StringUtils.substringAfter(uri, "/upload/"); key = StringUtils.substringBeforeLast(key, "?"); // Erase Qiniu template key = StringUtils.substringBeforeLast(key, "?"); // Erase Qiniu template String path = UPLOAD_DIR + key; path = URLDecoder.decode(path, "UTF-8"); 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" + SoloServletListener.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); }