List of usage examples for org.apache.commons.lang StringUtils substring
public static String substring(String str, int start)
Gets a substring from the specified String avoiding exceptions.
From source file:org.artifactory.api.maven.MavenArtifactInfo.java
public static MavenArtifactInfo fromRepoPath(RepoPath repoPath) { String groupId, artifactId, version, type = MavenArtifactInfo.NA, classifier = MavenArtifactInfo.NA; String path = repoPath.getPath(); String fileName = repoPath.getName(); //The format of the relative path in maven is a/b/c/artifactId/baseVer/fileName where //groupId="a.b.c". We split the path to elements and analyze the needed fields. LinkedList<String> pathElements = new LinkedList<>(); StringTokenizer tokenizer = new StringTokenizer(path, "/"); while (tokenizer.hasMoreTokens()) { pathElements.add(tokenizer.nextToken()); }// w ww .j a v a2 s . c o m //Sanity check, we need groupId, artifactId and version if (pathElements.size() < 3) { log.debug( "Cannot build MavenArtifactInfo from '{}'. The groupId, artifactId and version are unreadable.", repoPath); return new MavenArtifactInfo(); } //Extract the version, artifactId and groupId int pos = pathElements.size() - 2; // one before the last path element version = pathElements.get(pos--); artifactId = pathElements.get(pos--); StringBuilder groupIdBuff = new StringBuilder(); for (; pos >= 0; pos--) { if (groupIdBuff.length() != 0) { groupIdBuff.insert(0, '.'); } groupIdBuff.insert(0, pathElements.get(pos)); } groupId = groupIdBuff.toString(); //Extract the type and classifier except for metadata files boolean metaData = NamingUtils.isMetadata(fileName); if (!metaData) { if (MavenNaming.isUniqueSnapshotFileName(fileName)) { version = StringUtils.remove(version, "-" + MavenNaming.SNAPSHOT); version = version + "-" + MavenNaming.getUniqueSnapshotVersionTimestampAndBuildNumber(fileName); } type = StringUtils.substring(fileName, artifactId.length() + version.length() + 2); int versionStartIndex = StringUtils.indexOf(fileName, "-", artifactId.length()) + 1; int classifierStartIndex = StringUtils.indexOf(fileName, "-", versionStartIndex + version.length()); if (classifierStartIndex >= 0) { Set<String> customMavenTypes = getMavenCustomTypes(); for (String customMavenType : customMavenTypes) { if (StringUtils.endsWith(fileName, customMavenType)) { classifier = StringUtils.remove(type, "." + customMavenType); type = customMavenType; break; } } if (MavenArtifactInfo.NA.equals(classifier)) { int typeDotStartIndex = StringUtils.lastIndexOf(type, "."); classifier = StringUtils.substring(type, 0, typeDotStartIndex); type = StringUtils.substring(type, classifier.length() + 1); } } } return new MavenArtifactInfo(groupId, artifactId, version, classifier, type); }
From source file:org.beangle.struts2.convention.route.Profile.java
/** * ???.?/<br>// w ww. ja va 2 s .com * ?/ * * @param clazz * @param profile * @return */ public String getInfix(String className) { String postfix = getActionSuffix(); String simpleName = className.substring(className.lastIndexOf('.') + 1); if (StringUtils.contains(simpleName, postfix)) { simpleName = StringUtils.uncapitalize(simpleName.substring(0, simpleName.length() - postfix.length())); } else { simpleName = StringUtils.uncapitalize(simpleName); } MatchInfo match = getCtlMatchInfo(className); StringBuilder infix = new StringBuilder(match.getReserved().toString()); if (infix.length() > 0) { infix.append('.'); } String remainder = StringUtils.substring(StringUtils.substringBeforeLast(className, "."), match.getStartIndex() + 1); if (remainder.length() > 0) { infix.append(remainder).append('.'); } if (infix.length() == 0) return simpleName; infix.append(simpleName); // .??/ for (int i = 0; i < infix.length(); i++) { if (infix.charAt(i) == '.') { infix.setCharAt(i, '/'); } } return infix.toString(); }
From source file:org.bigmouth.nvwa.utils.url.URLDecoder.java
/** * URL???/* ww w .j a v a 2 s . c om*/ * * @param <T> * @param url * ?URL? * <ul> * <li>http://www.big-mouth.cn/nvwa-utils/xml/decoder?id=123&json_data=bbb</li> * <li>/nvwa-utils/xml/decoder?id=123&json_data=bbb</li> * <li>id=123&json_data=bbb</li> * </li> * </ul> * @param cls * @return * @throws Exception */ public static <T> T decode(String url, Class<T> cls) throws Exception { if (StringUtils.isBlank(url)) return null; T t = cls.newInstance(); String string = null; if (StringUtils.contains(url, "?")) { string = StringUtils.substringAfter(url, "?"); } else { int start = StringUtils.indexOf(url, "?") + 1; string = StringUtils.substring(url, start); } Map<String, Object> attrs = Maps.newHashMap(); String[] kvs = StringUtils.split(string, "&"); for (String kv : kvs) { String[] entry = StringUtils.split(kv, "="); if (entry.length <= 1) { continue; } else if (entry.length == 2) { attrs.put(entry[0], entry[1]); } else { List<String> s = Lists.newArrayList(entry); s.remove(0); attrs.put(entry[0], StringUtils.join(s.toArray(new String[0]), "=")); } } Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { // if the field name is 'appId' String fieldName = field.getName(); String paramName = fieldName; if (field.isAnnotationPresent(Argument.class)) { paramName = field.getAnnotation(Argument.class).name(); } // select appId node Object current = attrs.get(paramName); if (null == current) { // select appid node current = attrs.get(paramName.toLowerCase()); } if (null == current) { // select APPID node current = attrs.get(paramName.toUpperCase()); } if (null == current) { // select app_id node String nodename = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(paramName), "_") .toLowerCase(); current = attrs.get(nodename); } if (null == current) { // select APP_ID node String nodename = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(paramName), "_") .toUpperCase(); current = attrs.get(nodename); } if (null != current) { String invokeName = StringUtils.join(new String[] { "set", StringUtils.capitalize(fieldName) }); try { MethodUtils.invokeMethod(t, invokeName, current); } catch (NoSuchMethodException e) { LOGGER.warn("NoSuchMethod-" + invokeName); } catch (IllegalAccessException e) { LOGGER.warn("IllegalAccess-" + invokeName); } catch (InvocationTargetException e) { LOGGER.warn("InvocationTarget-" + invokeName); } } } return t; }
From source file:org.eclipse.emf.emfstore.internal.common.model.util.FileUtil.java
/** * Returns the extension of the given file. * // www . ja v a 2 s . c o m * @param file * the file whose extension should be determined * @return the file extension, if any, otherwise empty string */ public static String getExtension(File file) { final int lastIndexOf = file.getName().lastIndexOf("."); //$NON-NLS-1$ if (lastIndexOf == -1) { return StringUtils.EMPTY; } return StringUtils.substring(file.getName(), lastIndexOf); }
From source file:org.eclipse.gyrex.cloud.internal.queue.ZooKeeperQueue.java
/** * Returns a sorted map of the queue node children. * // w w w .j av a 2s . c o m * @param monitor * optional watcher * @return map with key sequence number and value child name * @throws KeeperException * @throws IllegalStateException */ private TreeMap<Long, String> readQueueChildren(final ZooKeeperMonitor monitor) throws InterruptedException, IllegalStateException, KeeperException { final TreeMap<Long, String> childrenBySequenceNumber = new TreeMap<Long, String>(); final Collection<String> childNames = ZooKeeperGate.get().readChildrenNames(queuePath, monitor, null); for (final String childName : childNames) { if (!StringUtils.startsWith(childName, PREFIX)) { LOG.warn("Incorrect child name {} in queue {}.", new Object[] { childName, id }); continue; } final long sequenceNumber = NumberUtils.toLong(StringUtils.substring(childName, PREFIX.length()), -1); if (sequenceNumber < 0) { LOG.warn("Incorrect sequence number in child name {} in queue {}.", new Object[] { childName, id }); continue; } childrenBySequenceNumber.put(sequenceNumber, childName); } return childrenBySequenceNumber; }
From source file:org.ednovo.gooru.controllers.BaseController.java
public String generateUri(String uri, String id) { StringBuilder sb = new StringBuilder(StringUtils.substring(uri, 14)); sb.append(RequestMappingUri.SEPARATOR).append(id); return sb.toString(); }
From source file:org.fornax.utilities.xtendtools.lib.StringsExtension.java
/** * Delegate for StringUtils.substring.//ww w .ja va 2s . com * * @see StringUtils#substring(String, int) */ public static String substring(final String str, final Integer start) { return StringUtils.substring(str, start); }
From source file:org.gaixie.micrite.common.search.SearchFactory.java
private static String[] detach(String str, char left, char right) { String string = str;/*from www.j a v a2 s . c om*/ if (string == null || string.equals("")) return null; List<String> list = new ArrayList<String>(); if (StringUtils.indexOf(string, left) == -1 || StringUtils.indexOf(string, right) == -1) throw new RasterFormatException("??: " + string); while (StringUtils.indexOf(string, left) >= 0 && StringUtils.indexOf(string, right) >= 0) { int il = StringUtils.indexOf(string, left); int ir = StringUtils.indexOf(string, right); if (il > ir) { string = StringUtils.substring(string, right + 1); continue; } list.add(StringUtils.substring(string, il + 1, ir)); string = StringUtils.substring(string, ir + 1); } return list.toArray(new String[list.size()]); }
From source file:org.intermine.webservice.server.complexes.ExportService.java
private String getComplexIdentifier() { String identifier = StringUtils.substring(request.getPathInfo(), 1); if (StringUtils.isBlank(identifier)) { throw new BadRequestException("No identifier provided"); }//from w ww. j a va 2 s. com return identifier; }
From source file:org.jahia.services.importexport.LegacyImportHandler.java
private boolean setPropertyField(ExtendedNodeType baseType, String localName, JCRNodeWrapper node, String propertyName, String value, Map<String, String> creationMetadata) throws RepositoryException { JCRNodeWrapper parent = node;/*ww w. j a va 2 s . c om*/ String mixinType = null; if (propertyName.contains("|")) { mixinType = StringUtils.substringBefore(propertyName, "|"); propertyName = StringUtils.substringAfter(propertyName, "|"); } if (StringUtils.contains(propertyName, "/")) { String parentPath = StringUtils.substringBeforeLast(propertyName, "/"); if (parent.hasNode(parentPath)) { parent = parent.getNode(parentPath); } propertyName = StringUtils.substringAfterLast(propertyName, "/"); } parent = checkoutNode(parent); if (!StringUtils.isEmpty(mixinType) && !parent.isNodeType(mixinType)) { parent.addMixin(mixinType); } ExtendedPropertyDefinition propertyDefinition; propertyDefinition = parent.getApplicablePropertyDefinition(propertyName); if (propertyDefinition == null) { return false; } if (propertyDefinition.isProtected()) { return false; } if (StringUtils.isNotBlank(value) && !value.equals("<empty>")) { Node n = parent; if (propertyDefinition.isInternationalized()) { n = getOrCreateI18N(parent, locale, creationMetadata); } if (!n.isCheckedOut()) { session.checkout(n); } switch (propertyDefinition.getRequiredType()) { case PropertyType.DATE: GregorianCalendar cal = new GregorianCalendar(); try { DateFormat df = new SimpleDateFormat(ImportExportService.DATE_FORMAT); Date d = df.parse(value); cal.setTime(d); n.setProperty(propertyName, cal); } catch (java.text.ParseException e) { logger.error(e.getMessage(), e); } break; case PropertyType.REFERENCE: case PropertyType.WEAKREFERENCE: if (propertyDefinition.isMultiple()) { String[] strings = Patterns.TRIPPLE_DOLLAR.split(value); for (String s : strings) { createReferenceValue(s, propertyDefinition.getSelector(), n, propertyName); } } else { createReferenceValue(value, propertyDefinition.getSelector(), n, propertyName); } break; default: switch (propertyDefinition.getSelector()) { case SelectorType.RICHTEXT: { if (value.contains("=\"###")) { int count = 1; StringBuilder buf = new StringBuilder(value); while (buf.indexOf("=\"###") > -1) { int from = buf.indexOf("=\"###") + 2; int to = buf.indexOf("\"", from); String ref = buf.substring(from, to); if (ref.startsWith("###/webdav")) { ref = StringUtils.substringAfter(ref, "###/webdav"); buf.replace(from, to, "##doc-context##/{workspace}/##ref:link" + count + "##"); } else if (ref.startsWith("###file:")) { ref = StringUtils.substringAfter(ref, "###file:"); final int qmPos = ref.indexOf('?'); boolean isUuid = false; if (qmPos != -1) { if (StringUtils.substring(ref, qmPos + 1).startsWith("uuid=default:")) { ref = StringUtils.substring(ref, qmPos + 14); isUuid = true; } else ref = StringUtils.substringBefore(ref, "?"); } if (!isUuid) ref = correctFilename(ref); buf.replace(from, to, "##doc-context##/{workspace}/##ref:link" + count + "##"); } else { ref = StringUtils.substringAfterLast(ref, "/"); // we keep the URL parameters if any String params = ""; int pos = ref.indexOf('?'); if (pos == -1) { pos = ref.indexOf('#'); } if (pos != -1) { params = ref.substring(pos); ref = ref.substring(0, pos); } buf.replace(from, to, "##cms-context##/{mode}/{lang}/##ref:link" + count + "##.html" + params); } try { ref = URLDecoder.decode(ref, "UTF-8"); } catch (UnsupportedEncodingException e) { } if (!references.containsKey(ref)) { references.put(ref, new ArrayList<String>()); } references.get(ref) .add(n.getIdentifier() + "/[" + count + "]" + propertyDefinition.getName()); count++; } value = buf.toString(); } n.setProperty(propertyName, value); if (logger.isDebugEnabled()) logger.debug("Setting on node " + n.getPath() + " property " + propertyName + " with value=" + value); break; } default: { String[] vcs = propertyDefinition.getValueConstraints(); List<String> constraints = Arrays.asList(vcs); if (!propertyDefinition.isMultiple()) { if (value.startsWith("<jahia-resource")) { value = ResourceBundleMarker.parseMarkerValue(value).getResourceKey(); if (value.startsWith(propertyDefinition.getResourceBundleKey())) { value = value.substring(propertyDefinition.getResourceBundleKey().length() + 1); } } else if ("jcr:description".equals(propertyName)) { value = removeHtmlTags(value); } value = baseType != null ? mapping.getMappedPropertyValue(baseType, localName, value) : value; if (valueMatchesContraints(value, constraints)) { try { n.setProperty(propertyName, value); if (logger.isDebugEnabled()) logger.debug("Setting on node " + n.getPath() + " property " + propertyName + " with value=" + value); } catch (Exception e) { logger.error("Impossible to set property " + propertyName + " due to exception", e); } } else { logger.error( "Impossible to set property " + propertyName + " due to some constraint error"); logger.error(" - value = " + value); logger.error(" - constraints = " + constraints.toString()); } } else { String[] strings = Patterns.TRIPPLE_DOLLAR.split(value); List<Value> values = new ArrayList<Value>(); for (String string : strings) { if (string.startsWith("<jahia-resource")) { string = ResourceBundleMarker.parseMarkerValue(string).getResourceKey(); if (string.startsWith(propertyDefinition.getResourceBundleKey())) { string = string .substring(propertyDefinition.getResourceBundleKey().length() + 1); } } value = baseType != null ? mapping.getMappedPropertyValue(baseType, localName, value) : value; if (constraints.isEmpty() || constraints.contains(value)) { values.add(new ValueImpl(string, propertyDefinition.getRequiredType())); } } n.setProperty(propertyName, values.toArray(new Value[values.size()])); if (logger.isDebugEnabled()) logger.debug("Setting on node " + n.getPath() + " property " + propertyName + " with value=" + values); } break; } } } } else { return false; } return true; }