Example usage for org.apache.commons.lang3 StringUtils substring

List of usage examples for org.apache.commons.lang3 StringUtils substring

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils substring.

Prototype

public static String substring(final String str, int start, int end) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

A negative start position can be used to start/end n characters from the end of the String.

The returned substring starts with the character in the start position and ends before the end position.

Usage

From source file:gov.ca.cwds.cals.service.mapper.PlacementHomeMapper.java

/**
 * Sets facility name.//from w  w w  .j  a v a  2s  .  c  om
 * <p>
 * Facility's name must not be more than 50 characters long,
 * PrmCnctnm must not be more than 35 chars long and PrmSubsnm must not be more than 50 chars long
 * so we just cut out extra characters.
 * </p>
 *
 * @param placementHome entity
 * @param form form DTO
 */
@AfterMapping
default void setFacilityName(@MappingTarget PlacementHome placementHome, RFA1aFormDTO form) {
    StringBuilder sb = new StringBuilder(PlacementHomeUtil.composeFacilityName(form.getApplicants()))
            .append(" RFH");
    placementHome.setFacltyNm(StringUtils.substring(sb.toString(), 0, 50));
    Optional.ofNullable(Applicant.getPrimary(form)).ifPresent(applicantDTO -> {
        placementHome.setPrmCnctnm(StringUtils.substring(Applicant.getFirstLastName(applicantDTO), 0, 35));
        placementHome.setPrmSubsnm(StringUtils.substring(applicantDTO.getApplicantFullName(), 0, 50));
    });
}

From source file:de.micromata.genome.logging.spi.ifiles.IndexDirectory.java

public void renameFile(File oldFile, File newFile) throws IOException {
    String oldName = getDirectoryNameFromFile(oldFile);

    indexByteBuffer.position(HEADER_SIZE);
    byte[] nameBuffer = new byte[LOG_FILE_NAME_SIZE];
    while (indexByteBuffer.position() + ROW_SIZE < indexChannel.size()) {
        indexByteBuffer.getInt();//from   ww  w .j a va2  s. c om
        indexByteBuffer.get(nameBuffer);
        String trimmed = new String(nameBuffer).trim();
        String fnt = StringUtils.substring(oldName, 0, LOG_FILE_NAME_SIZE);
        if (StringUtils.equalsIgnoreCase(trimmed, fnt) == true) {
            String lwwrite = fileToStoredName(newFile);
            indexByteBuffer.position(indexByteBuffer.position() - LOG_FILE_NAME_SIZE);
            indexByteBuffer.put(lwwrite.getBytes(StandardCharsets.US_ASCII));
            break;
        }

    }
}

From source file:de.micromata.tpsb.doc.parser.JavaDocUtil.java

/**
 * Parst einen JavaDoc Tag// w w  w.  jav  a 2 s  . c  o m
 * 
 * @param tag der Tag-String
 * @param tagMap die zu befllende Tag-Map
 */
private static void parseTag(String tag, Map<String, List<Pair<String, String>>> tagMap) {
    final String TUPEL_PATTERN = "^(%s)(.*)$";
    final String TRIPEL_PATTERN = "^(@\\S*)\\s(\\S*)(.*)$";
    int idx = StringUtils.indexOf(tag, " ");
    String tagName = StringUtils.substring(tag, 0, idx);

    String pattern = tupelTags.contains(tagName) ? TUPEL_PATTERN : TRIPEL_PATTERN;
    Pattern p = Pattern.compile(String.format(pattern, tagName), Pattern.DOTALL);
    Matcher matcher = p.matcher(tag);
    String key = null;
    String val = null;
    if (matcher.matches() == true) {
        switch (matcher.groupCount()) {
        case 2:
            val = matcher.group(2).trim();
            break;
        case 3:
            key = matcher.group(2).trim();
            val = matcher.group(3).trim();
            break;
        default:
            System.out.println("Kein Match");
        }
        if (tagMap.get(tagName) == null) {
            tagMap.put(tagName, new ArrayList<Pair<String, String>>());
        }
        tagMap.get(tagName).add(Pair.make(key, val));
    }
}

From source file:com.moviejukebox.reader.MovieNFOReader.java

/**
 * Try and read a NFO file for information
 *
 * First try as XML format file, then check to see if it contains XML and text and split it to read each part
 *
 * @param nfoFile/*from  w  ww  .j  a  va 2s .  c o  m*/
 * @param movie
 * @return
 */
public static boolean readNfoFile(File nfoFile, Movie movie) {
    String nfoText = FileTools.readFileToString(nfoFile);
    boolean parsedNfo = Boolean.FALSE; // Was the NFO XML parsed correctly or at all
    boolean hasXml = Boolean.FALSE;

    if (StringUtils.containsIgnoreCase(nfoText, XML_START + TYPE_MOVIE)
            || StringUtils.containsIgnoreCase(nfoText, XML_START + TYPE_TVSHOW)
            || StringUtils.containsIgnoreCase(nfoText, XML_START + TYPE_EPISODE)) {
        hasXml = Boolean.TRUE;
    }

    // If the file has XML tags in it, try reading it as a pure XML file
    if (hasXml) {
        parsedNfo = readXmlNfo(nfoFile, movie);
    }

    // If it has XML in it, but didn't parse correctly, try splitting it out
    if (hasXml && !parsedNfo) {
        int posMovie = findPosition(nfoText, TYPE_MOVIE);
        int posTv = findPosition(nfoText, TYPE_TVSHOW);
        int posEp = findPosition(nfoText, TYPE_EPISODE);
        int start = Math.min(posMovie, Math.min(posTv, posEp));

        posMovie = StringUtils.indexOf(nfoText, XML_END + TYPE_MOVIE);
        posTv = StringUtils.indexOf(nfoText, XML_END + TYPE_TVSHOW);
        posEp = StringUtils.indexOf(nfoText, XML_END + TYPE_EPISODE);
        int end = Math.max(posMovie, Math.max(posTv, posEp));

        if ((end > -1) && (end > start)) {
            end = StringUtils.indexOf(nfoText, '>', end) + 1;

            // Send text to be read
            String nfoTrimmed = StringUtils.substring(nfoText, start, end);
            parsedNfo = readXmlNfo(nfoTrimmed, movie, nfoFile.getName());

            nfoTrimmed = StringUtils.remove(nfoText, nfoTrimmed);
            if (parsedNfo && nfoTrimmed.length() > 0) {
                // We have some text left, so scan that with the text scanner
                readTextNfo(nfoTrimmed, movie);
            }
        }
    }

    // If the XML wasn't found or parsed correctly, then fall back to the old method
    if (parsedNfo) {
        LOG.debug("Successfully scanned {} as XML format", nfoFile.getName());
    } else {
        parsedNfo = MovieNFOReader.readTextNfo(nfoText, movie);
        if (parsedNfo) {
            LOG.debug("Successfully scanned {} as text format", nfoFile.getName());
        } else {
            LOG.debug("Failed to find any information in {}", nfoFile.getName());
        }
    }

    return Boolean.FALSE;
}

From source file:de.jcup.egradle.sdk.builder.action.javadoc.ReplaceJavaDocPartsAction.java

License:asdf

/**
 * Replace javadoc identifier tag and trailing parts: "@param name xyz" will
 * be transformed by "${replacement} xyz"
 * //from  w  w  w .j a v a 2  s  .co  m
 * @param text
 * @param javadocId
 * @param replacer
 * @param fetchFullLineAsContent
 *            when <code>true</code> the full line is used as content on
 *            replacement:<br>
 *            <br>
 * 
 *            <pre>
 * "@myTag bla xyz\n" will be replaced by "$replacedContentFor(bla) xyz\n"
 *            </pre>
 * 
 *            When <code>false</code>
 * 
 *            <pre>
 * "@myTag bla xyz\n" will be replaced by "$replacedContentFor(bla xyz)\n"
 *            </pre>
 * 
 * @return replaced string
 */
String replaceJavaDocTagAndTrailingParts(String text, String javadocId, ContentReplacer replacer,
        boolean fetchFullLineAsContent) {
    String result = text;
    while (true) {
        int index = result.indexOf(javadocId);
        if (index == -1) {
            return result;
        }

        String before = StringUtils.substring(result, 0, index);

        int length = result.length();
        StringBuilder content = new StringBuilder();
        boolean leadingWhiteSpaces = true;
        int pos = index + javadocId.length();

        while (pos < length) {
            char c = result.charAt(pos++);
            if (Character.isWhitespace(c)) {
                if (leadingWhiteSpaces) {
                    continue;
                }
                if (fetchFullLineAsContent) {
                    /* we only break when line ends */
                    if (c == '\n') {
                        pos--; // go back one step because after needs this
                               // maybe
                        break;
                    } else {
                        /*
                         * do nothing, simply add the whitespace itself too
                         */
                    }

                } else {
                    /*
                     * default way: every whitespace after leading ones will
                     * break
                     */
                    pos--;
                    break;
                }
            }
            leadingWhiteSpaces = false;
            content.append(c);
        }
        String after = StringUtils.substring(result, pos);
        String replaced = replacer.replace(content.toString());

        result = before + replaced + after;
    }
}

From source file:com.erudika.para.i18n.LanguageUtils.java

/**
 * Returns a non-null locale for a given language code.
 * @param langCode the 2-letter language code
 * @return a locale. default is English/*w  w  w . j av a 2  s. c o  m*/
 */
public Locale getProperLocale(String langCode) {
    langCode = StringUtils.substring(langCode, 0, 2);
    langCode = (StringUtils.isBlank(langCode) || !allLocales.containsKey(langCode)) ? "en"
            : langCode.trim().toLowerCase();
    return allLocales.get(langCode);
}

From source file:de.micromata.genome.db.jpa.tabattr.entities.JpaTabAttrBaseDO.java

/**
 * Set the value of the attribute./*from   w ww.  j ava 2 s  .  com*/
 * 
 * if value is longer than VALUE_MAXLENGHT the string will be split and stored in additional data children entities.
 *
 * @param value the new string data
 */
public void setStringData(String value) {
    List<JpaTabAttrDataBaseDO<?, PK>> data = getData();
    data.clear();
    int maxValLength = getValueMaxLength();
    if (StringUtils.length(value) > maxValLength) {
        this.value = value.substring(0, maxValLength);
        String rest = value.substring(maxValLength);
        int maxDataLength = getMaxDataLength();
        int rowIdx = 0;
        while (rest.length() > 0) {
            String ds = StringUtils.substring(rest, 0, maxDataLength);
            rest = StringUtils.substring(rest, maxDataLength);
            JpaTabAttrDataBaseDO<?, PK> dataDo = createData(ds);
            dataDo.setDatarow(rowIdx++);
            data.add(dataDo);
        }
    } else {
        this.value = value;
    }
}

From source file:com.dgtlrepublic.anitomyj.ParserNumber.java

/**
 * Checks if a number follows the specified {@code token}.
 *
 * @param category the category to set if a number follows the {@code token}.
 * @param token    the token/* w  w w .  j ava 2s.  c  om*/
 * @return true if a number follows the token; false otherwise
 */
public boolean numberComesAfterPrefix(ElementCategory category, Token token) {
    int number_begin = ParserHelper.indexOfFirstDigit(token.getContent());
    String prefix = StringUtils.substring(token.getContent(), 0, number_begin).toUpperCase(Locale.ENGLISH);
    if (KeywordManager.getInstance().contains(category, prefix)) {
        String number = StringUtils.substring(token.getContent(), number_begin, token.getContent().length());

        switch (category) {
        case kElementEpisodePrefix:
            if (!matchEpisodePatterns(number, token))
                setEpisodeNumber(number, token, false);
            return true;
        case kElementVolumePrefix:
            if (!matchVolumePatterns(number, token))
                setVolumeNumber(number, token, false);
            return true;
        }
    }

    return false;
}

From source file:com.erudika.scoold.utils.LanguageUtils.java

/**
 * Returns a non-null locale for a given language code.
 * @param langCode the 2-letter language code
 * @return a locale. default is English//from ww  w  . j a  va 2s .c o  m
 */
public Locale getProperLocale(String langCode) {
    if (StringUtils.startsWith(langCode, "zh")) {
        if ("zh_tw".equalsIgnoreCase(langCode)) {
            return Locale.TRADITIONAL_CHINESE;
        } else {
            return Locale.SIMPLIFIED_CHINESE;
        }
    }
    String lang = StringUtils.substring(langCode, 0, 2);
    lang = (StringUtils.isBlank(lang) || !ALL_LOCALES.containsKey(lang)) ? "en" : lang.trim().toLowerCase();
    return ALL_LOCALES.get(lang);
}

From source file:com.joyent.manta.client.MantaClientRangeIT.java

public final void canGetWithZeroRange() throws IOException {
    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;
    final String expected = StringUtils.substring(TEST_DATA, 0, 1);

    mantaClient.put(path, TEST_DATA);//  w w w.ja  v  a2  s . c  o m

    final MantaHttpHeaders headers = new MantaHttpHeaders();
    // Range is inclusive, inclusive
    headers.setRange("bytes=0-0");

    try (final InputStream min = mantaClient.getAsInputStream(path, headers)) {
        String actual = IOUtils.toString(min, Charset.defaultCharset());
        Assert.assertEquals(actual, expected, "Didn't receive correct range value");
    }
}