Java Code Examples for org.apache.commons.lang3.StringUtils#lastIndexOf()

The following examples show how to use org.apache.commons.lang3.StringUtils#lastIndexOf() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FilenameUtils.java    From halo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets base name of file name. <br>
 * eg: <br>
 * filename: /home/test/test.txt <br>
 * basename: test
 *
 * @param filename filename must not be blank
 * @return basename of the given file name
 */
@NonNull
public static String getBasename(@NonNull String filename) {
    Assert.hasText(filename, "Filename must not be blank");

    // Find the last slash
    int separatorLastIndex = StringUtils.lastIndexOf(filename, File.separatorChar);

    if (separatorLastIndex == filename.length() - 1) {
        return StringUtils.EMPTY;
    }

    if (separatorLastIndex >= 0 && separatorLastIndex < filename.length() - 1) {
        filename = filename.substring(separatorLastIndex + 1);
    }

    // Find last dot
    int dotLastIndex = StringUtils.lastIndexOf(filename, '.');

    if (dotLastIndex < 0) {
        return filename;
    }

    return filename.substring(0, dotLastIndex);
}
 
Example 2
Source File: FilenameUtils.java    From halo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets extension of the file name. <br>
 * <code>
 * eg: <br>
 * filename: /home/test/test.txt <br>
 * extension: txt
 * </code>
 *
 * @param filename filename must not be blank
 * @return an extension of the given file name
 */
@NonNull
public static String getExtension(@NonNull String filename) {
    Assert.hasText(filename, "Filename must not be blank");

    // Find the last slash
    int separatorLastIndex = StringUtils.lastIndexOf(filename, File.separatorChar);

    if (separatorLastIndex == filename.length() - 1) {
        return StringUtils.EMPTY;
    }

    if (separatorLastIndex >= 0 && separatorLastIndex < filename.length() - 1) {
        filename = filename.substring(separatorLastIndex + 1);
    }

    // Find last dot
    int dotLastIndex = StringUtils.lastIndexOf(filename, '.');

    if (dotLastIndex < 0) {
        return StringUtils.EMPTY;
    }

    return filename.substring(dotLastIndex + 1);
}
 
Example 3
Source File: QueueUtils.java    From conductor with Apache License 2.0 6 votes vote down vote up
public static String getTaskType(String queue) {

		if(StringUtils.isBlank(queue)) {
			return StringUtils.EMPTY;
		}

		int domainSeperatorIndex = StringUtils.indexOf(queue, DOMAIN_SEPARATOR);
		int startIndex = 0;
		if (domainSeperatorIndex == -1) {
			startIndex = 0;
		} else {
			startIndex = domainSeperatorIndex +1 ;
		}
		int endIndex = StringUtils.indexOf(queue, EXECUTION_NAME_SPACE_SEPRATOR);

		if (endIndex == -1) {
			endIndex = StringUtils.lastIndexOf(queue, ISOLATION_SEPARATOR);
		}
		if (endIndex == -1) {
			endIndex = queue.length();
		}

		return StringUtils.substring(queue, startIndex, endIndex);
	}
 
Example 4
Source File: TextPositionUtils.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Calculates the line and offset delta contained in the text, i.e. how many lines the text
 * contains and how many characters it contains in the last line.
 *
 * @param text the text for which to calculate the deltas
 * @param lineSeparator the line separator contained in the text
 * @return a pair containing the line delta as the first/left element and the offset delta as the
 *     second/right element
 * @throws NullPointerException if the given text or line separator is <code>null</code>
 */
public static Pair<Integer, Integer> calculateDeltas(String text, String lineSeparator) {
  Objects.requireNonNull(text, "The given text must not be null");
  Objects.requireNonNull(lineSeparator, "The given line separator must not be null");

  if (text.isEmpty()) {
    return new ImmutablePair<>(0, 0);
  }

  int lineDelta = StringUtils.countMatches(text, lineSeparator);

  int offsetDelta;

  if (lineDelta == 0) {
    offsetDelta = text.length();

  } else {
    int lastLineStart = StringUtils.lastIndexOf(text, lineSeparator) + lineSeparator.length();

    offsetDelta = text.length() - lastLineStart;
  }

  return new ImmutablePair<>(lineDelta, offsetDelta);
}
 
Example 5
Source File: MotanUtils.java    From pepper-metrics with Apache License 2.0 5 votes vote down vote up
public static String getShortName(String str) {
    if (StringUtils.isNotEmpty(str)) {
        final int i1 = StringUtils.lastIndexOf(str, '.');
        final int i2 = StringUtils.lastIndexOf(str, '.', i1 - 1);
        return StringUtils.substring(str, i2 + 1);
    }
    return str;
}
 
Example 6
Source File: ProcessRemarkServiceImpl.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param originalElementHtml
 * @param truncatedElementHtml
 * @param indexOfElementToClose
 * @return 
 */
private String closeInnerElement (
        String originalElementHtml, 
        String truncatedElementHtml) {
    
    int startPos = truncatedElementHtml.length();
    
    int indexOfElementCloser = 
            StringUtils.indexOf(originalElementHtml, ESCAPED_CLOSE_TAG, startPos);
    int indexOfElementAutoCloser = 
            StringUtils.indexOf(originalElementHtml, AUTO_CLOSE_TAG_OCCUR, startPos);
    
    
    String innerClosedElement = StringUtils.substring(
            originalElementHtml, 
            0, 
            (indexOfElementCloser+ESCAPED_CLOSE_TAG.length()));
    
    // if the current element is auto-close, return current well-closed element
    if (indexOfElementAutoCloser == (indexOfElementCloser-1) ) {
        return innerClosedElement;
    }
    
    // if the current element is not auto-close, get the name of it and 
    // and properly close it
    int indexOfElementOpenTagOpener = 
            StringUtils.lastIndexOf(originalElementHtml, ESCAPED_OPEN_TAG, startPos);
    
    int indexOfElementOpenTagClose = 
            StringUtils.indexOf(originalElementHtml, ' ', indexOfElementOpenTagOpener);
    
    String elementName = 
            StringUtils.substring(
                originalElementHtml, 
                indexOfElementOpenTagOpener + ESCAPED_OPEN_TAG.length(), 
                indexOfElementOpenTagClose);

    return closeElement(innerClosedElement, elementName);
}
 
Example 7
Source File: AbstractDownloadableLinkRuleImplementation.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param uri
 * @return whether the current link has a proper extension (link.html)
 */
private boolean isLinkWithProperExtension(URI uri) {
    if (StringUtils.isNotBlank(uri.getQuery())) {
        return false;
    }
    String path = uri.getPath();
    if (StringUtils.isBlank(path) || 
            StringUtils.equals(path, SLASH_CHAR)) {
        return false;
    }
    int lastSlash = StringUtils.lastIndexOf(path, SLASH_CHAR);
    return StringUtils.substring(path, lastSlash).contains(POINT_CHAR);
}
 
Example 8
Source File: VectorUtil.java    From Alink with Apache License 2.0 4 votes vote down vote up
/**
 * Parse the sparse vector from a formatted string.
 *
 * <p>The format of a sparse vector is space separated index-value pairs, such as "0:1 2:3 3:4".
 * If the sparse vector has determined vector size, the size is prepended to the head. For example,
 * the string "$4$0:1 2:3 3:4" represents a sparse vector with size 4.
 *
 * @throws IllegalArgumentException If the string is of invalid format.
 */
public static SparseVector parseSparse(String str) {
	try {
		if (org.apache.flink.util.StringUtils.isNullOrWhitespaceOnly(str)) {
			return new SparseVector();
		}

		int n = -1;
		int firstDollarPos = str.indexOf(HEADER_DELIMITER);
		int lastDollarPos = -1;
		if (firstDollarPos >= 0) {
			lastDollarPos = StringUtils.lastIndexOf(str, HEADER_DELIMITER);
			String sizeStr = StringUtils.substring(str, firstDollarPos + 1, lastDollarPos);
			n = Integer.valueOf(sizeStr);
			if (lastDollarPos == str.length() - 1) {
				return new SparseVector(n);
			}
		}

		int numValues = StringUtils.countMatches(str, String.valueOf(INDEX_VALUE_DELIMITER));
		double[] data = new double[numValues];
		int[] indices = new int[numValues];
		int startPos = lastDollarPos + 1;
		int endPos;
		for (int i = 0; i < numValues; i++) {
			int colonPos = StringUtils.indexOf(str, INDEX_VALUE_DELIMITER, startPos);
			if (colonPos < 0) {
				throw new IllegalArgumentException("Format error.");
			}
			endPos = StringUtils.indexOf(str, ELEMENT_DELIMITER, colonPos);

			//to be compatible with previous delimiter
			if (endPos == -1) {
				endPos = StringUtils.indexOf(str, ",", colonPos);
			}

			if (endPos == -1) {
				endPos = str.length();
			}
			indices[i] = Integer.valueOf(str.substring(startPos, colonPos).trim());
			data[i] = Double.valueOf(str.substring(colonPos + 1, endPos).trim());
			startPos = endPos + 1;
		}
		return new SparseVector(n, indices, data);
	} catch (Exception e) {
		throw new IllegalArgumentException(
			String.format("Fail to getVector sparse vector from string: \"%s\".", str),
			e);
	}
}
 
Example 9
Source File: LastIndexOf.java    From vscrawler with Apache License 2.0 4 votes vote down vote up
@Override
protected  int handleIndex(CharSequence str, CharSequence searchStr, int startPos) {
    return StringUtils.lastIndexOf(str, searchStr, startPos);
}
 
Example 10
Source File: Path.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static String relativeToAbsolute(String currentPath, String relativePath) {
    //begin with /
    if (relativePath.startsWith(File.separator)) {
        return relativePath;
    }

    String path = currentPath;
    File f = new File(currentPath);
    if (f.isFile()) {
        path = FilenameUtils.getPath(currentPath);
    }


    //begin with . means current path
    if (!relativePath.startsWith("..")) {
        if (relativePath.startsWith(".")) {
            return joinWithFilename(relativePath.substring(1), currentPath);
        } else {
            return joinWithFilename(relativePath, currentPath);
        }
    }

    //begin with .. means back path
    int count = StringUtils.countMatches(relativePath, "..");
    if (path.endsWith(File.separator)) {
        path = path.substring(0, path.length() - 1);
    }

    int idx = StringUtils.lastIndexOf(relativePath, "..");
    String realpath = relativePath.substring(idx + 1);

    String[] paths = StringUtils.split(path, File.separatorChar);
    int basepathCount = paths.length - count;
    if (0 > basepathCount) throw new RuntimeException("parent folder is so short.");
    if (0 == basepathCount) return realpath;
    String[] basePaths = new String[basepathCount];
    for (int i = 0; i < basepathCount; i++) {
        basePaths[i] = paths[i];
    }

    String basepath = StringUtils.join(basePaths, File.separator);
    return joinWithFilename(realpath, basepath);
}
 
Example 11
Source File: AbstractRuleImplementationTestCase.java    From Asqatasun with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public String getName(){
    int lastPointIndex = StringUtils.lastIndexOf(ruleImplementationClassName, ".")+1;
    String className = StringUtils.substring(ruleImplementationClassName, lastPointIndex);
    return StringUtils.replace(className, "Rule", "-");
}
 
Example 12
Source File: VectorUtil.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Parse the sparse vector from a formatted string.
 *
 * <p>The format of a sparse vector is space separated index-value pairs, such as "0:1 2:3 3:4".
 * If the sparse vector has determined vector size, the size is prepended to the head. For example,
 * the string "$4$0:1 2:3 3:4" represents a sparse vector with size 4.
 *
 * @param str A formatted string representing a sparse vector.
 * @throws IllegalArgumentException If the string is of invalid format.
 */
public static SparseVector parseSparse(String str) {
	try {
		if (org.apache.flink.util.StringUtils.isNullOrWhitespaceOnly(str)) {
			return new SparseVector();
		}

		int n = -1;
		int firstDollarPos = str.indexOf(HEADER_DELIMITER);
		int lastDollarPos = -1;
		if (firstDollarPos >= 0) {
			lastDollarPos = StringUtils.lastIndexOf(str, HEADER_DELIMITER);
			String sizeStr = StringUtils.substring(str, firstDollarPos + 1, lastDollarPos);
			n = Integer.valueOf(sizeStr);
			if (lastDollarPos == str.length() - 1) {
				return new SparseVector(n);
			}
		}

		int numValues = StringUtils.countMatches(str, String.valueOf(INDEX_VALUE_DELIMITER));
		double[] data = new double[numValues];
		int[] indices = new int[numValues];
		int startPos = lastDollarPos + 1;
		int endPos;
		for (int i = 0; i < numValues; i++) {
			int colonPos = StringUtils.indexOf(str, INDEX_VALUE_DELIMITER, startPos);
			if (colonPos < 0) {
				throw new IllegalArgumentException("Format error.");
			}
			endPos = StringUtils.indexOf(str, ELEMENT_DELIMITER, colonPos);

			if (endPos == -1) {
				endPos = str.length();
			}
			indices[i] = Integer.valueOf(str.substring(startPos, colonPos).trim());
			data[i] = Double.valueOf(str.substring(colonPos + 1, endPos).trim());
			startPos = endPos + 1;
		}
		return new SparseVector(n, indices, data);
	} catch (Exception e) {
		throw new IllegalArgumentException(
			String.format("Fail to getVector sparse vector from string: \"%s\".", str), e);
	}
}