List of usage examples for org.apache.commons.lang3 StringUtils removeEnd
public static String removeEnd(final String str, final String remove)
Removes a substring only if it is at the end of a source string, otherwise returns the source string.
A null source string will return null .
From source file:broadwick.phylo.NewickTreeParser.java
/** * Parse a given string that MUST be a valid Newick format. * @param newickStr the string to parse. * @return a Tree created from the parsed string. *///from w w w .j a va2 s. c o m public final Tree<PhyloNode, Edge<PhyloNode>> parse(final String newickStr) { branchLabel = 0; final Tree<PhyloNode, Edge<PhyloNode>> phyloTree = new Tree<>(); // first remove the trailing ; if any String stringToParse = StringUtils.removeEnd(newickStr.trim(), ";").trim(); if (stringToParse.charAt(0) == '(' && getClosingParenthesis(stringToParse) == stringToParse.length() - 1) { stringToParse = stringToParse.substring(1, stringToParse.length() - 1); } // extract the information for the root node, this will be after the last closing parenthesis iff there is // a colon (TODO is this right? e.g. (A,B,(C,D),E)F; ) double distance = 0.0; String rootName = ""; final int rparen = stringToParse.lastIndexOf(')'); final int rcolon = stringToParse.lastIndexOf(':'); if (rparen < rcolon) { distance = Double.parseDouble(stringToParse.substring(rcolon + 1)); rootName = stringToParse.substring(rparen + 1, rcolon); stringToParse = stringToParse.substring(0, rcolon - rootName.length()).trim(); // adjust the string to exclude the distance } // create a new node for this root and add it to the tree. final PhyloNode root = new PhyloNode(rootName, distance); log.trace("Parsing Newick file: Adding root node {}", root); phyloTree.addVertex(root); // if we don't have a comma we are just have the root node if (stringToParse.indexOf(',') == -1) { return phyloTree; } if (stringToParse.charAt(0) == '(' && getClosingParenthesis(stringToParse) == stringToParse.length() - 1) { stringToParse = stringToParse.substring(1, stringToParse.length() - 1); } parseString(stringToParse, root, phyloTree); return phyloTree; }
From source file:com.jayway.restassured.internal.print.RequestPrinter.java
public static String print(FilterableRequestSpecification requestSpec, String requestMethod, String completeRequestUri, LogDetail logDetail, PrintStream stream, boolean shouldPrettyPrint) { final StringBuilder builder = new StringBuilder(); if (logDetail == ALL || logDetail == METHOD) { addSingle(builder, "Request method:", requestMethod); }/* ww w . j a v a 2 s . c o m*/ if (logDetail == ALL || logDetail == PATH) { addSingle(builder, "Request path:", completeRequestUri); } if (logDetail == ALL) { addProxy(requestSpec, builder); } if (logDetail == ALL || logDetail == PARAMS) { addMapDetails(builder, "Request params:", requestSpec.getRequestParams()); addMapDetails(builder, "Query params:", requestSpec.getQueryParams()); addMapDetails(builder, "Form params:", requestSpec.getFormParams()); addMapDetails(builder, "Path params:", requestSpec.getNamedPathParams()); addMultiParts(requestSpec, builder); } if (logDetail == ALL || logDetail == HEADERS) { addHeaders(requestSpec, builder); } if (logDetail == ALL || logDetail == COOKIES) { addCookies(requestSpec, builder); } if (logDetail == ALL || logDetail == BODY) { addBody(requestSpec, builder, shouldPrettyPrint); } String logString = builder.toString(); if (logString.endsWith("\n")) { logString = StringUtils.removeEnd(logString, "\n"); } stream.println(logString); return logString; }
From source file:io.cloudslang.lang.compiler.Extension.java
public static String removeExtension(String fileName) { Extension extension = findExtension(fileName); if (extension != null) { return StringUtils.removeEnd(fileName, "." + extension.getValue()); }/* ww w . j a v a2s . com*/ return fileName; }
From source file:blue.lapis.pore.launch.PoreBootstrap.java
@Inject public PoreBootstrap(Injector injector) { URL location = getClass().getProtectionDomain().getCodeSource().getLocation(); String path = location.getPath(); if (location.getProtocol().equals("jar")) { int pos = path.lastIndexOf('!'); if (pos >= 0) { path = path.substring(0, pos + 2); }//from w ww .j a va 2 s . com } else { path = StringUtils.removeEnd(path, getClass().getName().replace('.', '/') + ".class"); } try { ClassLoader loader = new PoreClassLoader(getClass().getClassLoader(), new URL(location.getProtocol(), location.getHost(), location.getPort(), path)); Class<?> poreClass = Class.forName(IMPLEMENTATION_CLASS, true, loader); this.pore = (PoreEventManager) injector.getInstance(poreClass); } catch (ClassNotFoundException e) { throw new RuntimeException("Failed to load Pore implementation", e); } catch (MalformedURLException e) { throw new RuntimeException("Failed to load Pore implementation", e); } }
From source file:com.quartercode.femtoweb.impl.ActionUriResolver.java
/** * Returns the URI of the given {@link Action} which must be located in the given package. * See {@link Context#getUri(Class)} for more information. * * @param actionBasePackage The package name which will be removed from the start of the action class name. * Thereby, package names like {@code com.quartercode.femtowebtest.actions} are not included in URIs. * @param action The action class whose URI should be returned. * @return The URI the given action class is mapped to. *///from w w w .j a v a 2 s . co m public static String getUri(String actionBasePackage, Class<? extends Action> action) { String actionFQCN = action.getName(); // Verify that the action class is // - not an inner class // - not called "Action" // - ends with action Validate.isTrue(!StringUtils.contains(actionFQCN, '$'), "Action classes are not allowed to be inner classes; '%s' is therefore invalid", actionFQCN); Validate.isTrue(!actionFQCN.endsWith(".Action"), "Actions classes which are just called 'Action' are disallowed"); Validate.isTrue(actionFQCN.endsWith("Action"), "Actions classes must end with 'Action'; '%s' is therefore invalid", actionFQCN); // Verify that the action class is inside the base package Validate.isTrue(actionFQCN.startsWith(actionBasePackage), "Cannot retrieve URI of action class '%s' because it doesn't start with the set action base package '%s'", actionFQCN, actionBasePackage); // Retrieve the name of the action class without the base package String actionName = actionFQCN.substring(actionBasePackage.length() + 1); // Replace all "." with "/", add an "/" to the front, uncapitalize the last URI part, remove "Action" from the last URI part // Example: "path.to.SomeTestAction" -> "/path/to/someTest") String[] actionNameComponents = splitAtLastSeparator(actionName, "."); String uriDir = actionNameComponents[0].replace('.', '/'); String uriName = StringUtils.uncapitalize(StringUtils.removeEnd(actionNameComponents[1], "Action")); return "/" + joinNonBlankItems("/", uriDir, uriName); }
From source file:io.redlink.solrlib.standalone.SolrServerConnector.java
public SolrServerConnector(Set<SolrCoreDescriptor> coreDescriptors, SolrServerConnectorConfiguration configuration, ExecutorService executorService) { super(coreDescriptors, executorService); this.configuration = configuration; prefix = StringUtils.defaultString(configuration.getPrefix()); solrBaseUrl = StringUtils.removeEnd(configuration.getSolrUrl(), "/"); initialized = new AtomicBoolean(false); }
From source file:io.ecarf.core.compress.NTripleGzipProcessor.java
/** * @param inputFile/* w w w . j ava 2 s .co m*/ * @param outputFile */ public NTripleGzipProcessor(String inputFile) { super(); this.inputFile = inputFile; // get the file name before the ext String ext = FilenameUtils.getExtension(inputFile); // construct an output file in the format inputfile_out.ext this.outputFile = StringUtils.removeEnd(inputFile, "." + ext); this.outputFile = outputFile + Constants.OUT_FILE_SUFFIX + ext; }
From source file:com.adobe.acs.commons.wcm.vanity.impl.VanityURLServiceImpl.java
public boolean dispatch(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException, RepositoryException { if (request.getAttribute(VANITY_DISPATCH_CHECK_ATTR) != null) { log.trace("Processing a previously vanity dispatched request. Skipping..."); return false; }//from w w w.j a va 2 s .c om request.setAttribute(VANITY_DISPATCH_CHECK_ATTR, true); final String requestURI = request.getRequestURI(); final RequestPathInfo mappedPathInfo = new PathInfo(request.getResourceResolver(), requestURI); final String candidateVanity = mappedPathInfo.getResourcePath(); final String pathScope = StringUtils.removeEnd(requestURI, candidateVanity); log.debug("Candidate vanity URL to check and dispatch: [ {} ]", candidateVanity); // Check if... // 1) the candidateVanity and the requestURI are the same; If they are it means the request has already // gone through resource resolution and failed so there is no sense in sending it through again. // 2) the candidate is in at least 1 sling:vanityPath under /content if (!StringUtils.equals(candidateVanity, requestURI) && isVanityPath(pathScope, candidateVanity, request)) { log.debug("Forwarding request to vanity resource [ {} ]", candidateVanity); final RequestDispatcher requestDispatcher = request.getRequestDispatcher(candidateVanity); requestDispatcher.forward(new ExtensionlessRequestWrapper(request), response); return true; } return false; }
From source file:egovframework.com.utl.wed.filter.CkImageSaver.java
public CkImageSaver(String imageBaseDir, String imageDomain, String[] allowFileTypeArr, String saveManagerClass) { this.imageBaseDir = imageBaseDir; if (imageBaseDir.endsWith("/")) { StringUtils.removeEnd(imageBaseDir, "/"); }/* www . j a v a 2 s . c o m*/ if (imageBaseDir.endsWith("\\")) { StringUtils.removeEnd(imageBaseDir, "\\"); } this.imageDomain = imageDomain; if (imageDomain.endsWith("/")) { StringUtils.removeEnd(imageDomain, "/"); } this.allowFileTypeArr = allowFileTypeArr; if (StringUtils.isBlank(saveManagerClass)) { fileSaveManager = new DefaultFileSaveManager(); } else { try { Class<?> klass = Class.forName(saveManagerClass); fileSaveManager = (FileSaveManager) klass.newInstance(); } catch (ClassNotFoundException e) { log.error(e); throw new RuntimeException(e); } catch (InstantiationException e) { log.error(e); throw new RuntimeException(e); } catch (IllegalAccessException e) { log.error(e); throw new RuntimeException(e); } } }
From source file:com.infinities.nova.middleware.NoAuthMiddleware.java
protected void baseCall(ContainerRequestContext req, boolean projectIdInPath) throws Exception { logger.debug("NoAuthMiddleware begin"); if (!req.getHeaders().containsKey("X-Auth-Token")) { String userId = req.getHeaderString("X-Auth-User"); if (Strings.isNullOrEmpty(userId)) { userId = "admin"; }/* ww w .ja v a2s. com*/ String projectId = req.getHeaderString("X-Auth-Project-Id"); if (Strings.isNullOrEmpty(projectId)) { projectId = "{projectId}"; } String osUrl = null; if (projectIdInPath) { String url = StringUtils.removeEnd(req.getUriInfo().getRequestUri().toString(), "/"); osUrl = Joiner.on("/").join(new String[] { url, projectId }); } else { osUrl = StringUtils.removeEnd(req.getUriInfo().getRequestUri().toString(), "/"); } Response res = Response.status(204).header("X-Auth-Token", String.format("%s:%s", projectId, userId)) .header("X-Server-Management-Url", osUrl).type("text/plain").build(); req.abortWith(res); return; } String token = req.getHeaderString("X-Auth-Token"); String split[] = token.split(":"); String projectId = split[0]; String userId = split[0]; if (split.length >= 3) { projectId = split[2]; } String remoteAddress = httpRequest.getRemoteAddr(); if (Strings.isNullOrEmpty(remoteAddress)) { remoteAddress = "127.0.0.1"; } boolean useForwardedFor = Config.Instance.getOpt("use_forwarded_for").asBoolean(); if (useForwardedFor) { remoteAddress = req.getHeaderString("X-Forwarded-For"); if (Strings.isNullOrEmpty(remoteAddress)) { remoteAddress = "127.0.0.1"; } } NovaRequestContext ctx = new NovaRequestContext(userId, projectId, true, "no", null, remoteAddress, null, null, null, true, null, null, null, null, false); req.setProperty("nova.context", ctx); logger.debug("NoAuthMiddleware end"); }