Example usage for org.apache.commons.lang StringUtils removeStartIgnoreCase

List of usage examples for org.apache.commons.lang StringUtils removeStartIgnoreCase

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils removeStartIgnoreCase.

Prototype

public static String removeStartIgnoreCase(String str, String remove) 

Source Link

Document

Case insensitive removal of a substring if it is at the begining of a source string, otherwise returns the source string.

Usage

From source file:adalid.commons.velocity.Writer.java

private void createDirectories(String name, String[] stringArray) {
    String root = getRoot().getPath();
    String raiz = root.replace('\\', '/');
    String rama, pattern, message;
    String hint = "; check property: {0}={1}";
    Path path;/*from ww w  .ja v a 2s.  co  m*/
    Arrays.sort(stringArray);
    for (String string : stringArray) {
        if (StringUtils.isBlank(string)) {
            pattern = "directory name is missing" + hint;
            message = MessageFormat.format(pattern, name, string);
            log(_alertLevel, message);
            warnings++;
            continue;
        }
        try {
            path = Paths.get(string);
        } catch (InvalidPathException e) {
            pattern = ThrowableUtils.getString(e) + hint;
            message = MessageFormat.format(pattern, name, string);
            log(_alertLevel, message);
            warnings++;
            continue;
        }
        rama = StringUtils.removeStartIgnoreCase(string, raiz);
        log(_trackingLevel, "about to create directory " + rama);
        if (path.toFile().mkdirs()) {
            log(Level.INFO, "directory " + rama + " was created, along with all necessary parent directories");
        }
    }
}

From source file:adalid.commons.velocity.Writer.java

private void deletePreviouslyGeneratedFiles(String name, String[] stringArray, boolean recursive) {
    String root = getRoot().getPath();
    String raiz = root.replace('\\', '/');
    String path, pathname, wildcard;
    String recursively = recursive ? "and all its subdirectories" : "";
    String slashedPath, regex, pattern, message;
    String hint = "; check property: {0}={1}";
    boolean delete;
    File directory;/*from w ww .  j  a v a 2 s  .c  om*/
    IOFileFilter fileFilter;
    IOFileFilter dirFilter = recursive ? ignoreVersionControlFilter : null;
    Collection<File> matchingFiles;
    Arrays.sort(stringArray);
    for (String string : stringArray) {
        pathname = StringUtils.substringBeforeLast(string, SLASH);
        if (StringUtils.isBlank(string) || !StringUtils.contains(string, SLASH)
                || StringUtils.isBlank(pathname)) {
            pattern = "directory is missing or invalid" + hint;
            message = MessageFormat.format(pattern, name, string);
            log(_alertLevel, message);
            warnings++;
            continue;
        }
        wildcard = StringUtils.substringAfterLast(string, SLASH);
        if (StringUtils.isBlank(wildcard)) {
            pattern = "wildcard is missing or invalid" + hint;
            message = MessageFormat.format(pattern, name, string);
            log(_alertLevel, message);
            warnings++;
            continue;
        }
        directory = new File(pathname);
        if (FilUtils.isNotWritableDirectory(directory)) {
            pattern = "{2} is not a writable directory" + hint;
            message = MessageFormat.format(pattern, name, string,
                    StringUtils.removeStartIgnoreCase(pathname, raiz));
            log(_alertLevel, message);
            warnings++;
            continue;
        }
        log(_detailLevel, "deleting files " + wildcard + " from "
                + StringUtils.removeStartIgnoreCase(pathname, raiz) + " " + recursively);
        fileFilter = new WildcardFileFilter(wildcard);
        matchingFiles = FileUtils.listFiles(directory, fileFilter, dirFilter);
        for (File file : matchingFiles) {
            path = file.getPath();
            slashedPath = path.replace('\\', '/');
            delete = true;
            for (Pattern fxp : filePreservationPatterns) {
                regex = fxp.pattern();
                if (slashedPath.matches(regex)) {
                    delete = false;
                    pattern = "file {0} will not be deleted; it matches preservation expression \"{1}\"";
                    message = MessageFormat.format(pattern,
                            StringUtils.removeStartIgnoreCase(slashedPath, raiz), regex);
                    log(_alertLevel, message);
                    warnings++;
                    break;
                }
            }
            if (delete) {
                logger.trace("deleting " + StringUtils.removeStartIgnoreCase(path, root));
                FileUtils.deleteQuietly(file);
            }
        }
    }
}

From source file:adalid.core.programmers.AbstractSqlProgrammer.java

private String removeStart(String string, String[] searchStrings) {
    String s = StringUtils.trimToEmpty(string);
    String p;/*from   w  w  w  .j  ava2  s  .  c o  m*/
    for (String searchString : searchStrings) {
        if (StringUtils.isNotBlank(searchString)) {
            p = StringUtils.trimToEmpty(searchString);
            if (StringUtils.startsWithIgnoreCase(s, p)) {
                return StringUtils.trimToEmpty(StringUtils.removeStartIgnoreCase(s, p));
            }
        }
    }
    return s;
}

From source file:org.apache.tomcat.maven.plugin.tomcat8.run.RunMojo.java

@Override
protected void enhanceContext(final Context context) throws MojoExecutionException {
    super.enhanceContext(context);

    try {/*  w  w  w.j a v  a 2 s  . c om*/
        ClassLoaderEntriesCalculatorRequest request = new ClassLoaderEntriesCalculatorRequest() //
                .setDependencies(dependencies) //
                .setLog(getLog()) //
                .setMavenProject(project) //
                .setAddWarDependenciesInClassloader(addWarDependenciesInClassloader) //
                .setUseTestClassPath(useTestClasspath);
        final ClassLoaderEntriesCalculatorResult classLoaderEntriesCalculatorResult = classLoaderEntriesCalculator
                .calculateClassPathEntries(request);
        final List<String> classLoaderEntries = classLoaderEntriesCalculatorResult.getClassPathEntries();
        final List<File> tmpDirectories = classLoaderEntriesCalculatorResult.getTmpDirectories();

        final List<String> jarPaths = extractJars(classLoaderEntries);

        List<URL> urls = new ArrayList<URL>(jarPaths.size());

        for (String jarPath : jarPaths) {
            try {
                urls.add(new File(jarPath).toURI().toURL());
            } catch (MalformedURLException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
        }

        getLog().debug("classLoaderEntriesCalculator urls: " + urls);

        final URLClassLoader urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]));

        final ClassRealm pluginRealm = getTomcatClassLoader();

        context.setResources(
                new MyDirContext(new File(project.getBuild().getOutputDirectory()).getAbsolutePath(), //
                        getPath(), //
                        getLog()) {
                    @Override
                    public WebResource getClassLoaderResource(String path) {

                        log.debug("RunMojo#getClassLoaderResource: " + path);
                        URL url = urlClassLoader.getResource(StringUtils.removeStart(path, "/"));
                        // search in parent (plugin) classloader
                        if (url == null) {
                            url = pluginRealm.getResource(StringUtils.removeStart(path, "/"));
                        }

                        if (url == null) {
                            // try in reactors
                            List<WebResource> webResources = findResourcesInDirectories(path, //
                                    classLoaderEntriesCalculatorResult.getBuildDirectories());

                            // so we return the first one
                            if (!webResources.isEmpty()) {
                                return webResources.get(0);
                            }
                        }

                        if (url == null) {
                            return new EmptyResource(this, getPath());
                        }

                        return urlToWebResource(url, path);
                    }

                    @Override
                    public WebResource getResource(String path) {
                        log.debug("RunMojo#getResource: " + path);
                        return super.getResource(path);
                    }

                    @Override
                    public WebResource[] getResources(String path) {
                        log.debug("RunMojo#getResources: " + path);
                        return super.getResources(path);
                    }

                    @Override
                    protected WebResource[] getResourcesInternal(String path, boolean useClassLoaderResources) {
                        log.debug("RunMojo#getResourcesInternal: " + path);
                        return super.getResourcesInternal(path, useClassLoaderResources);
                    }

                    @Override
                    public WebResource[] getClassLoaderResources(String path) {
                        try {
                            Enumeration<URL> enumeration = urlClassLoader
                                    .findResources(StringUtils.removeStart(path, "/"));
                            List<URL> urlsFound = new ArrayList<URL>();
                            List<WebResource> webResources = new ArrayList<WebResource>();
                            while (enumeration.hasMoreElements()) {
                                URL url = enumeration.nextElement();
                                urlsFound.add(url);
                                webResources.add(urlToWebResource(url, path));
                            }
                            log.debug("RunMojo#getClassLoaderResources: " + path + " found : "
                                    + urlsFound.toString());

                            webResources.addAll(findResourcesInDirectories(path,
                                    classLoaderEntriesCalculatorResult.getBuildDirectories()));

                            return webResources.toArray(new WebResource[webResources.size()]);

                        } catch (IOException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        }
                    }

                    private List<WebResource> findResourcesInDirectories(String path,
                            List<String> directories) {
                        try {
                            List<WebResource> webResources = new ArrayList<WebResource>();

                            for (String directory : directories) {

                                File file = new File(directory, path);
                                if (file.exists()) {
                                    webResources.add(urlToWebResource(file.toURI().toURL(), path));
                                }

                            }

                            return webResources;
                        } catch (MalformedURLException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        }
                    }

                    private WebResource urlToWebResource(URL url, String path) {
                        JarFile jarFile = null;

                        try {
                            // url.getFile is
                            // file:/Users/olamy/mvn-repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar!/org/springframework/web/context/ContextLoaderListener.class

                            int idx = url.getFile().indexOf('!');

                            if (idx >= 0) {
                                String filePath = StringUtils.removeStart(url.getFile().substring(0, idx),
                                        "file:");

                                jarFile = new JarFile(filePath);

                                JarEntry jarEntry = jarFile.getJarEntry(StringUtils.removeStart(path, "/"));

                                return new JarResource(this, //
                                        getPath(), //
                                        filePath, //
                                        url.getPath().substring(0, idx), //
                                        jarEntry, //
                                        "", //
                                        null);
                            } else {
                                return new FileResource(this, webAppPath, new File(url.getFile()), true);
                            }

                        } catch (IOException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        } finally {
                            IOUtils.closeQuietly(jarFile);
                        }
                    }

                });

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                for (File tmpDir : tmpDirectories) {
                    try {
                        FileUtils.deleteDirectory(tmpDir);
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        });

        if (classLoaderEntries != null) {
            WebResourceSet webResourceSet = new FileResourceSet() {
                @Override
                public WebResource getResource(String path) {

                    if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) {
                        File file = new File(StringUtils.removeStartIgnoreCase(path, "/WEB-INF/LIB"));
                        return new FileResource(context.getResources(), getPath(), file, true);
                    }
                    if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) {
                        return new FileResource(context.getResources(), getPath(),
                                new File(project.getBuild().getOutputDirectory()), true);
                    }

                    File file = new File(project.getBuild().getOutputDirectory(), path);
                    if (file.exists()) {
                        return new FileResource(context.getResources(), getPath(), file, true);
                    }

                    //if ( StringUtils.endsWith( path, ".class" ) )
                    {
                        // so we search the class file in the jars
                        for (String jarPath : jarPaths) {
                            File jar = new File(jarPath);
                            if (!jar.exists()) {
                                continue;
                            }

                            try (JarFile jarFile = new JarFile(jar)) {
                                JarEntry jarEntry = (JarEntry) jarFile
                                        .getEntry(StringUtils.removeStart(path, "/"));
                                if (jarEntry != null) {
                                    return new JarResource(context.getResources(), //
                                            getPath(), //
                                            jarFile.getName(), //
                                            jar.toURI().toString(), //
                                            jarEntry, //
                                            path, //
                                            jarFile.getManifest());
                                }
                            } catch (IOException e) {
                                getLog().debug("skip error building jar file: " + e.getMessage(), e);
                            }

                        }
                    }

                    return new EmptyResource(null, path);
                }

                @Override
                public String[] list(String path) {
                    if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) {
                        return jarPaths.toArray(new String[jarPaths.size()]);
                    }
                    if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) {
                        return new String[] { new File(project.getBuild().getOutputDirectory()).getPath() };
                    }
                    return super.list(path);
                }

                @Override
                public Set<String> listWebAppPaths(String path) {

                    if (StringUtils.equalsIgnoreCase("/WEB-INF/lib/", path)) {
                        // adding outputDirectory as well?
                        return new HashSet<String>(jarPaths);
                    }

                    File filePath = new File(getWarSourceDirectory(), path);

                    if (filePath.isDirectory()) {
                        Set<String> paths = new HashSet<String>();

                        String[] files = filePath.list();
                        if (files == null) {
                            return paths;
                        }

                        for (String file : files) {
                            paths.add(file);
                        }

                        return paths;

                    } else {
                        return Collections.emptySet();
                    }
                }

                @Override
                public boolean mkdir(String path) {
                    return super.mkdir(path);
                }

                @Override
                public boolean write(String path, InputStream is, boolean overwrite) {
                    return super.write(path, is, overwrite);
                }

                @Override
                protected void checkType(File file) {
                    //super.checkType( file );
                }

            };

            context.getResources().addJarResources(webResourceSet);
        }

    } catch (TomcatRunException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}

From source file:org.awesomeagile.testing.google.FakeGoogleController.java

private void validateAuthorization(String authorizationHeader) {
    if (StringUtils.startsWithIgnoreCase(authorizationHeader, BEARER)) {
        if (knownTokens.contains(StringUtils.removeStartIgnoreCase(authorizationHeader, BEARER).trim())) {
            return;
        }/*from ww  w . ja  v a 2 s.c o  m*/
    }
    throw new BadCredentialsException("Invalid authorization header: " + authorizationHeader);
}

From source file:org.ednovo.gooru.domain.service.resource.ResourceServiceImpl.java

private String cleanTitle(String title) {
    final List<String> stringsToRemoveList = Arrays.asList("bbc", "ks2", "read", "phet", "bitesize", "maths");
    Set stringsToRemoveSet = new HashSet<String>(stringsToRemoveList);

    while (true) {
        title = StringUtils.trim(title);
        title = StringUtils.removeStart(title, ",");
        title = StringUtils.removeStart(title, ".");
        title = StringUtils.removeStart(title, "-");
        title = StringUtils.removeStart(title, ":");
        title = StringUtils.removeEnd(title, ",");
        title = StringUtils.removeEnd(title, ".");
        title = StringUtils.removeEnd(title, "-");
        title = StringUtils.removeEnd(title, ":");
        title = StringUtils.trim(title);

        String[] words = StringUtils.split(title, ": ");
        if (words.length > 0 && stringsToRemoveSet.contains(words[0].toLowerCase())) {
            title = StringUtils.removeStartIgnoreCase(title, words[0]);
        } else if (words.length > 0 && stringsToRemoveSet.contains(words[words.length - 1].toLowerCase())) {
            title = StringUtils.removeEndIgnoreCase(title, words[words.length - 1]);
        } else {//from  w  w  w  . j ava2 s.com
            break;
        }
    }
    return title;
}

From source file:org.jenkinsci.plugins.pipeline.maven.util.XmlUtils.java

/**
 * Relativize path/*from  w w w  .j  a  v  a  2  s  .co  m*/
 * <p>
 * TODO replace all the workarounds (JENKINS-44088, JENKINS-46084, mac special folders...) by a unique call to
 * {@link File#getCanonicalPath()} on the workspace for the whole "MavenSpyLogProcessor#processMavenSpyLogs" code block.
 * We donb't want to pay an RPC call to {@link File#getCanonicalPath()} each time.
 *
 * @return relativized path
 * @throws IllegalArgumentException if {@code other} is not a {@code Path} that can be relativized
 *                                  against this path
 * @see java.nio.file.Path#relativize(Path)
 */
@Nonnull
public static String getPathInWorkspace(@Nonnull final String absoluteFilePath, @Nonnull FilePath workspace) {
    boolean windows = isWindows(workspace);

    final String workspaceRemote = workspace.getRemote();

    String sanitizedAbsoluteFilePath;
    String sanitizedWorkspaceRemote;
    if (windows) {
        // sanitize to workaround JENKINS-44088
        sanitizedWorkspaceRemote = workspaceRemote.replace('/', '\\');
        sanitizedAbsoluteFilePath = absoluteFilePath.replace('/', '\\');
    } else if (workspaceRemote.startsWith("/var/") && absoluteFilePath.startsWith("/private/var/")) {
        // workaround MacOSX special folders path
        // eg String workspace = "/var/folders/lq/50t8n2nx7l316pwm8gc_2rt40000gn/T/jenkinsTests.tmp/jenkins3845105900446934883test/workspace/build-on-master-with-tool-provided-maven";
        // eg String absolutePath = "/private/var/folders/lq/50t8n2nx7l316pwm8gc_2rt40000gn/T/jenkinsTests.tmp/jenkins3845105900446934883test/workspace/build-on-master-with-tool-provided-maven/pom.xml";
        sanitizedWorkspaceRemote = workspaceRemote;
        sanitizedAbsoluteFilePath = absoluteFilePath.substring("/private".length());
    } else {
        sanitizedAbsoluteFilePath = absoluteFilePath;
        sanitizedWorkspaceRemote = workspaceRemote;
    }

    if (StringUtils.startsWithIgnoreCase(sanitizedAbsoluteFilePath, sanitizedWorkspaceRemote)) {
        // OK
    } else if (sanitizedWorkspaceRemote.contains("/workspace/")
            && sanitizedAbsoluteFilePath.contains("/workspace/")) {
        // workaround JENKINS-46084
        // sanitizedAbsoluteFilePath = '/app/Jenkins/home/workspace/testjob/pom.xml'
        // sanitizedWorkspaceRemote = '/var/lib/jenkins/workspace/testjob'
        sanitizedAbsoluteFilePath = "/workspace/"
                + StringUtils.substringAfter(sanitizedAbsoluteFilePath, "/workspace/");
        sanitizedWorkspaceRemote = "/workspace/"
                + StringUtils.substringAfter(sanitizedWorkspaceRemote, "/workspace/");
    } else if (sanitizedWorkspaceRemote.endsWith("/workspace")
            && sanitizedAbsoluteFilePath.contains("/workspace/")) {
        // workspace = "/var/lib/jenkins/jobs/Test-Pipeline/workspace";
        // absolutePath = "/storage/jenkins/jobs/Test-Pipeline/workspace/pom.xml";
        sanitizedAbsoluteFilePath = "workspace/"
                + StringUtils.substringAfter(sanitizedAbsoluteFilePath, "/workspace/");
        sanitizedWorkspaceRemote = "workspace/";
    } else {
        throw new IllegalArgumentException(
                "Cannot relativize '" + absoluteFilePath + "' relatively to '" + workspace.getRemote() + "'");
    }

    String relativePath = StringUtils.removeStartIgnoreCase(sanitizedAbsoluteFilePath,
            sanitizedWorkspaceRemote);
    String fileSeparator = windows ? "\\" : "/";

    if (relativePath.startsWith(fileSeparator)) {
        relativePath = relativePath.substring(fileSeparator.length());
    }
    LOGGER.log(Level.FINEST, "getPathInWorkspace({0}, {1}: {2}",
            new Object[] { absoluteFilePath, workspaceRemote, relativePath });
    return relativePath;
}

From source file:org.jfrog.build.extractor.maven.BuildInfoRecorder.java

@Override
public void sessionStarted(ExecutionEvent event) {
    try {/* w  w w . j a v a  2s.  c  o  m*/
        logger.info("Initializing Artifactory Build-Info Recording");
        buildInfoBuilder = buildInfoModelPropertyResolver.resolveProperties(event, conf);
        deployableArtifactBuilderMap = Maps.newHashMap();
        matrixParams = Maps.newHashMap();
        Map<String, String> matrixParamProps = conf.publisher.getMatrixParams();
        for (Map.Entry<String, String> matrixParamProp : matrixParamProps.entrySet()) {
            String key = matrixParamProp.getKey();
            key = StringUtils.removeStartIgnoreCase(key, ClientProperties.PROP_DEPLOY_PARAM_PROP_PREFIX);
            matrixParams.put(key, matrixParamProp.getValue());
        }

        if (wrappedListener != null) {
            wrappedListener.sessionStarted(event);
        }
    } catch (Throwable t) {
        String message = getClass().getName() + ".sessionStarted() listener has failed: ";
        logger.error(message, t);
        throw new RuntimeException(message, t);
    }
}

From source file:org.jfrog.teamcity.agent.BaseBuildInfoExtractor.java

private void addBuildVariables(BuildInfoBuilder builder, IncludeExcludePatterns patterns) {
    Map<String, String> allParamMap = Maps.newHashMap();
    allParamMap.putAll(runnerContext.getBuildParameters().getAllParameters());
    allParamMap.putAll(((BuildRunnerContextEx) runnerContext).getConfigParameters());
    for (Map.Entry<String, String> entryToAdd : allParamMap.entrySet()) {
        String key = entryToAdd.getKey();
        if (key.startsWith(Constants.ENV_PREFIX)) {
            key = StringUtils.removeStartIgnoreCase(key, Constants.ENV_PREFIX);
        } else if (key.startsWith(Constants.SYSTEM_PREFIX)) {
            key = StringUtils.removeStartIgnoreCase(key, Constants.SYSTEM_PREFIX);
        }/*from  w  w  w .  ja v a 2  s. c om*/
        if (PatternMatcher.pathConflicts(key, patterns)) {
            continue;
        }
        builder.addProperty(BuildInfoProperties.BUILD_INFO_ENVIRONMENT_PREFIX + key, entryToAdd.getValue());
    }
}

From source file:org.jfrog.teamcity.agent.util.ArtifactoryClientConfigurationBuilder.java

private static void addEnvVars(BuildRunnerContext runnerContext, ArtifactoryClientConfiguration clientConf) {
    Map<String, String> allParamMap = Maps.newHashMap();
    allParamMap.putAll(runnerContext.getBuildParameters().getAllParameters());
    allParamMap.putAll(((BuildRunnerContextEx) runnerContext).getConfigParameters());

    HashMap<String, String> allVars = Maps.newHashMapWithExpectedSize(allParamMap.size());
    for (Map.Entry<String, String> entryToAdd : allParamMap.entrySet()) {
        String key = entryToAdd.getKey();
        if (key.startsWith(Constants.ENV_PREFIX)) {
            key = StringUtils.removeStartIgnoreCase(key, Constants.ENV_PREFIX);
        } else if (key.startsWith(Constants.SYSTEM_PREFIX)) {
            key = StringUtils.removeStartIgnoreCase(key, Constants.SYSTEM_PREFIX);
        }/*from   ww w . ja  v  a  2 s  .  c o m*/
        allVars.put(key, entryToAdd.getValue());
    }

    IncludeExcludePatterns patterns = new IncludeExcludePatterns(clientConf.getEnvVarsIncludePatterns(),
            clientConf.getEnvVarsExcludePatterns());
    clientConf.info.addBuildVariables(allVars, patterns);
    clientConf.fillFromProperties(allVars, patterns);
}