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) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

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

A null String will return null .

Usage

From source file:de.jcup.egradle.codeassist.dsl.MethodUtils.java

/**
 * Calculates method identification in percentage (100= 100%).<br>
 * <br>//from w  w  w  . j  a v a2 s. co m
 * <ul>
 * <li>If a method is exact same 100% is returned</li>
 * <li>If a method is has same name, same param size, but x parameters of n
 * are not equal 50%-100% is returned</li>
 * <li>If a method is has same name, but param size is not equal 50% is
 * returned</li>
 * </ul>
 * 
 * @param method
 * @param itemIdentifier
 * @param itemParameters
 * @return percentage
 */
public static int calculateMethodIdentificationPercentage(Method method, String itemIdentifier,
        String... itemParameters) {
    if (method == null) {
        return 0;
    }
    if (itemIdentifier == null) {
        return 0;
    }
    String methodName = method.getName();
    if (methodName == null) {
        return 0;
    }
    if (itemParameters == null) {
        itemParameters = new String[] {};
    }
    int percentage;
    if (itemIdentifier.equals(methodName)) {
        percentage = 50;// 50% reached because name is equal
    } else {
        if (!methodName.startsWith("get") && !methodName.startsWith("set")) {
            return 0;
        }
        if (methodName.length() == 3) {
            return 0;
        }
        String methodPartName = StringUtils.substring(methodName, 3);
        String buildMethodPartName = StringUtils.capitalize(itemIdentifier);
        if (!methodPartName.equals(buildMethodPartName)) {
            return 0;
        }
        percentage = 49;// 49% reached because name is not equal but it
        // seems groovy magic for get/set,
        // 49% because if there would exists a method with
        // absolute same name this should matter more!
    }
    /* -------------------------------- */
    /* - start percentage calculation - */
    /* -------------------------------- */

    /* name okay, could be ... */

    List<Parameter> parameters = method.getParameters();
    /* check size same */
    int paramSize = parameters.size();
    if (paramSize != itemParameters.length) {
        return percentage;
    }

    if (paramSize == 0) {
        /* speed up and avoid failures on percentage calculation */
        return percentage + 50;
    }

    /* okay at least same size */
    int pos = 0;
    int percentPerCorrectParam = 50 / paramSize;

    int paramPercents = 0;
    boolean allParamsSame = true;
    for (Parameter p : parameters) {
        String itemParam = itemParameters[pos++];
        if (p == null) {
            /* should never happen */
            continue;
        }
        if (itemParam == null) {
            continue;
        }
        /*
         * if item parameter is with color we remove this meta information
         */
        itemParam = StringUtils.substringBefore(itemParam, ":");

        String typeAsString = p.getTypeAsString();
        if (!typeAsString.equals(itemParam)) {
            allParamsSame = false;
        } else {
            paramPercents += percentPerCorrectParam;
        }
    }
    if (allParamsSame) {
        percentage += 50;
    } else {
        if (paramPercents >= 50) {
            /* should never happen but... */
            paramPercents = 49;
        }
        percentage += paramPercents;
    }
    return percentage;
}

From source file:com.wallissoftware.pushstate.client.PushStateHistorianImpl.java

private String stripRelativePath(final String ptoken) {
    final String relPath = this.stripStartSlash(this.relativePath);
    final String token = this.stripStartSlash(ptoken);

    if (StringUtils.startsWith(token, relPath)) {
        return this.stripStartSlash(StringUtils.substring(token, relPath.length()));
    }// ww w . j  av  a2 s  . c  om
    return token;
}

From source file:com.commander4j.sys.JHostList.java

public boolean checkUpdatedHosts() {
    boolean result = false;

    if (Common.updateMODE.equals("AUTOMATIC")) {

        Double currentHostVersion = Double.valueOf(Common.hostVersion);
        logger.debug("Current Host File Version = " + String.valueOf(currentHostVersion));

        String hostUpdatePath = Common.hostUpdatePath;
        if (hostUpdatePath.equals("") == true) {

            logger.debug("No hosts file update location specified, checking application update url.");

            hostUpdatePath = Common.updateURL;
            if (hostUpdatePath.equals("") == true) {
                logger.debug("No application update location specified. Hosts update will not occur.");
            } else {

                hostUpdatePath = StringUtils.removeIgnoreCase(hostUpdatePath, "file:");

                int windowsDriveLetter = hostUpdatePath.indexOf(":");
                if (windowsDriveLetter > 0) {
                    hostUpdatePath = StringUtils.substring(hostUpdatePath, windowsDriveLetter - 1);
                }//w ww  . j a v  a  2  s  . c om

                hostUpdatePath = JUtility.formatPath(hostUpdatePath);
                hostUpdatePath = StringUtils.replaceIgnoreCase(hostUpdatePath, "updates.xml", "hosts.xml");
                logger.debug("Using application update url to check for updated hosts.");
            }
        }

        Common.hostUpdatePath = hostUpdatePath;

        // See if updatedHosts location specified
        if (hostUpdatePath.equals("") == false) {
            logger.debug("Updated Host Path = [" + hostUpdatePath + "]");
            if (Files.exists(Paths.get(hostUpdatePath))) {
                logger.debug("Updated Host Path = [" + hostUpdatePath + "] found.");

                Double updatedHostVersion = JXMLHost.checkHostVersion(hostUpdatePath);
                logger.debug("Updated Host File Version = " + String.valueOf(updatedHostVersion));

                if (updatedHostVersion > currentHostVersion) {
                    logger.debug("Copying Updated Host File [" + hostUpdatePath + "]");
                    try {
                        File destDir = new File(System.getProperty("user.dir") + File.separator + "xml"
                                + File.separator + "hosts");
                        File srcFile = new File(hostUpdatePath);
                        FileUtils.copyFileToDirectory(srcFile, destDir);
                        result = true;
                    } catch (Exception e) {
                        logger.debug("Error Copying Updated Host File :" + e.getMessage());
                    }
                } else {
                    logger.debug("Current hosts file is up to date " + currentHostVersion.toString());
                }
            } else {
                logger.debug("Updated Host Path = " + hostUpdatePath + " not found.");
            }
        }
    }

    return result;
}

From source file:jenkins.plugins.asqatasun.AsqatasunRunner.java

/**
 * //from www  .  j a v  a2 s  .  c o m
 * @param logFile
 * @param ps
 * @throws IOException 
 */
public void extractDataAndPrintOut(File logFile, PrintStream ps) throws IOException {
    ps.println("");
    boolean isFirstMark = true;
    boolean isFirstNbPassed = true;
    boolean isFirstNbFailed = true;
    boolean isFirstNbFailedOccurences = true;
    boolean isFirstNbNmi = true;
    boolean isFirstNbNa = true;
    boolean isFirstNbNt = true;
    for (Object obj : FileUtils.readLines(logFile)) {
        String line = (String) obj;
        if (StringUtils.startsWith(line, "Subject")) {
            ps.println("");
            ps.println(line);
        } else if (StringUtils.startsWith(line, "Audit terminated")) {
            ps.println(line);
        } else if (StringUtils.startsWith(line, "RawMark")) {
            ps.println(line.replace("RawMark", "Mark"));
            if (isFirstMark) {
                mark = StringUtils.substring(line, StringUtils.indexOf(line, ":") + 1).replaceAll("%", "")
                        .trim();
                isFirstMark = false;
            }
        } else if (StringUtils.startsWith(line, "Nb Passed")) {
            nbPassed = getNbStatus(ps, isFirstNbPassed, line);
            isFirstNbPassed = false;
        } else if (StringUtils.startsWith(line, "Nb Failed test")) {
            nbFailed = getNbStatus(ps, isFirstNbFailed, line);
            isFirstNbFailed = false;
        } else if (StringUtils.startsWith(line, "Nb Failed occurences")) {
            nbFailedOccurences = getNbStatus(ps, isFirstNbFailedOccurences, line);
            isFirstNbFailedOccurences = false;
        } else if (StringUtils.startsWith(line, "Nb Pre-qualified")) {
            nbNmi = getNbStatus(ps, isFirstNbNmi, line);
            isFirstNbNmi = false;
        } else if (StringUtils.startsWith(line, "Nb Not Applicable")) {
            nbNa = getNbStatus(ps, isFirstNbNa, line);
            isFirstNbNa = false;
        } else if (StringUtils.startsWith(line, "Nb Not Tested")) {
            nbNt = getNbStatus(ps, isFirstNbNt, line);
            isFirstNbNt = false;
        } else if (StringUtils.startsWith(line, "Audit Id")) {
            ps.println(line);
            auditId = StringUtils.substring(line, StringUtils.indexOf(line, ":") + 1).trim();
        }
    }
    ps.println("");
}

From source file:de.unentscheidbar.validation.builtin.Ipv4AddressValidator.java

@Override
protected void validateNonEmptyString(ValidationResult result, String s) {

    String[] parts = StringUtils.splitPreserveAllTokens(s, '.');

    /*/*from   w ww  . j  av  a 2  s .co  m*/
     * Number of segments ok?
     */
    if (parts.length < IPV4_SEGMENT_COUNT) {
        result.add(Id.TOO_FEW_SEGMENTS, s, parts.length);
        return;
    } else if (parts.length > IPV4_SEGMENT_COUNT) {
        result.add(Id.TOO_MANY_SEGMENTS, s, parts.length);
        return;
    }
    assert parts.length == IPV4_SEGMENT_COUNT;

    /* Handle bitmask modifier, if present (such as 10.37.0.0/16) */
    String maskStr = "";
    int maxIdx = parts.length - 1;
    int slashIndex = parts[maxIdx].lastIndexOf('/');
    if (slashIndex != -1) {
        maskStr = StringUtils.substring(parts[maxIdx], slashIndex + 1);
        parts[maxIdx] = parts[maxIdx].substring(0, slashIndex);
    }

    Integer bits = maskStr.isEmpty() ? Integer.valueOf(BITS_PER_IPV4) : Ints.tryParse(maskStr);
    if (bits == null || bits < minBits || bits > maxBits) {
        result.add(Id.BAD_SUBNET_MASK, bits == null ? maskStr : bits.toString(), minBits, maxBits);
        return;
    }
    for (int i = 0; i < parts.length; i++) {
        if (!BYTE_RANGE_VALIDATOR.wouldAcceptWithout(Severity.ERROR, parts[i])) {
            result.add(Id.SEGMENT_INVALID, i, parts[i]);
            break;
        }
    }
}

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

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

    mantaClient.put(path, TEST_DATA);//from  w  ww  .j  av a  2s  . c om

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

    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");
    }
}

From source file:ch.cyberduck.core.s3.S3SearchFeatureTest.java

@Test
public void testSearchInDirectory() throws Exception {
    final S3Session session = new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("s3.key"),
                    System.getProperties().getProperty("s3.secret"))));
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path workdir = new Path("test-us-east-1-cyberduck",
            EnumSet.of(Path.Type.directory, Path.Type.volume));
    workdir.attributes().setRegion("us-east-1");
    final String name = new AlphanumericRandomStringService().random();
    final Path file = new Path(workdir, name, EnumSet.of(Path.Type.file));
    session.getFeature(Touch.class).touch(file, new TransferStatus());
    final S3SearchFeature feature = new S3SearchFeature(session);
    assertTrue(/*w  w  w  . ja  v a2 s.  com*/
            feature.search(workdir, new SearchFilter(name), new DisabledListProgressListener()).contains(file));
    assertTrue(feature.search(workdir, new SearchFilter(StringUtils.substring(name, 2)),
            new DisabledListProgressListener()).contains(file));
    {
        final AttributedList<Path> result = feature.search(workdir,
                new SearchFilter(StringUtils.substring(name, 0, name.length() - 2)),
                new DisabledListProgressListener());
        assertTrue(result.contains(file));
    }
    assertFalse(feature.search(
            new Path(workdir, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)),
            new SearchFilter(name), new DisabledListProgressListener()).contains(file));
    final Path subdir = new S3DirectoryFeature(session, new S3WriteFeature(session)).mkdir(
            new Path(workdir, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)),
            null, new TransferStatus());
    assertFalse(
            feature.search(subdir, new SearchFilter(name), new DisabledListProgressListener()).contains(file));
    final Path filesubdir = new S3TouchFeature(session).touch(
            new Path(subdir, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)),
            new TransferStatus());
    {
        final AttributedList<Path> result = feature.search(workdir, new SearchFilter(filesubdir.getName()),
                new DisabledListProgressListener());
        assertNotNull(result.find(new SimplePathPredicate(filesubdir)));
        assertEquals(subdir, result.find(new SimplePathPredicate(filesubdir)).getParent());
    }
    new S3DefaultDeleteFeature(session).delete(Arrays.asList(file, filesubdir, subdir),
            new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}

From source file:gobblin.data.management.version.finder.DateTimeDatasetVersionFinder.java

/**
 * Parse {@link org.joda.time.DateTime} from {@link org.apache.hadoop.fs.Path} using datetime pattern.
 *//*from   www .jav a2  s .c o  m*/
@Override
public TimestampedDatasetVersion getDatasetVersion(Path pathRelativeToDatasetRoot,
        FileStatus versionFileStatus) {

    String dateTimeString = null;
    try {
        // pathRelativeToDatasetRoot can be daily/2016/03/02 or 2016/03/02. In either case we need to pick 2016/03/02 as version
        dateTimeString = StringUtils.substring(pathRelativeToDatasetRoot.toString(),
                pathRelativeToDatasetRoot.toString().length() - this.datePartitionPattern.length());

        return new FileStatusTimestampedDatasetVersion(this.formatter.parseDateTime(dateTimeString),
                versionFileStatus);

    } catch (IllegalArgumentException exception) {
        LOGGER.warn(String.format(
                "Candidate dataset version with pathRelativeToDatasetRoot: %s has inferred dataTimeString:%s. "
                        + "It does not match expected datetime pattern %s. Ignoring.",
                pathRelativeToDatasetRoot, dateTimeString, this.datePartitionPattern));
        return null;
    }
}

From source file:ch.cyberduck.core.b2.B2SearchFeatureTest.java

@Test
public void testSearchInRoot() throws Exception {
    final B2Session session = new B2Session(new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("b2.user"),
                    System.getProperties().getProperty("b2.key"))));
    final LoginConnectionService service = new LoginConnectionService(new DisabledLoginCallback(),
            new DisabledHostKeyCallback(), new DisabledPasswordStore(), new DisabledProgressListener());
    service.connect(session, PathCache.empty(), new DisabledCancelCallback());
    final String name = new AlphanumericRandomStringService().random();
    final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path file = new B2TouchFeature(session).touch(new Path(bucket, name, EnumSet.of(Path.Type.file)),
            new TransferStatus());
    final B2SearchFeature feature = new B2SearchFeature(session);
    assertNotNull(feature.search(bucket, new SearchFilter(name), new DisabledListProgressListener())
            .find(new SimplePathPredicate(file)));
    // Supports prefix matching only
    assertNull(feature/* w  w  w  . j  av  a2s .  c  om*/
            .search(new Path("/", EnumSet.of(Path.Type.directory, Path.Type.volume)),
                    new SearchFilter(StringUtils.substring(name, 2)), new DisabledListProgressListener())
            .find(new SimplePathPredicate(file)));
    assertNotNull(feature.search(new Path("/", EnumSet.of(Path.Type.directory, Path.Type.volume)),
            new SearchFilter(StringUtils.substring(name, 0, name.length() - 2)),
            new DisabledListProgressListener()).find(new SimplePathPredicate(file)));
    new B2DeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    session.close();
}

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

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

    mantaClient.put(path, TEST_DATA);/* w w  w . j a  v a2 s .  co  m*/

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

    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");
    }
}