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

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

Introduction

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

Prototype

public static String removeStart(String str, String remove) 

Source Link

Document

Removes a substring only if it is at the begining of a source string, otherwise returns the source string.

Usage

From source file:org.apache.sling.dynamicinclude.SyntheticResourceFilter.java

private static String getResourceTypeFromSuffix(SlingHttpServletRequest request) {
    final String suffix = request.getRequestPathInfo().getSuffix();
    return StringUtils.removeStart(suffix, "/");
}

From source file:org.apache.struts.maven.snippetextractor.parser.java.CommentParser.java

/**
 * Remove the java comment start pattern {@value #JAVA_COMMENT_START_STRING} from the start of
 * provided string. Whitespaces at the start are removed. If the java comment is a javadoc start, the second
 * asterisk is also removed. If no pattern is found the string is returned unchanged.
 *
 * @param string {@link String} which is to be stripped from the java comment start.
 * @return {@link String} without java comment or javadoc start or the unchanged string
 *///from  ww w  .  j  a v  a  2s  .c  o m
public static String removeCommentStart(String string) {
    String result = StringUtils.stripStart(string, " \t");
    if (!result.startsWith(CommentParser.JAVA_COMMENT_START_STRING)) {
        return string;
    }
    result = StringUtils.removeStart(result, CommentParser.JAVA_COMMENT_START_STRING);
    if (result.startsWith("*")) {
        result = result.substring(1);
    }
    return result;
}

From source file:org.apache.tika.server.resource.TikaResource.java

/**
 * Utility method to set a property on a class via reflection.
 *
 * @param httpHeaders the HTTP headers set.
 * @param object      the <code>Object</code> to set the property on.
 * @param key         the key of the HTTP Header.
 * @param prefix      the name of the HTTP Header prefix used to find property.
 * @throws WebApplicationException thrown when field cannot be found.
 *///from  w  w w  . j  av  a  2s  . c om
private static void processHeaderConfig(MultivaluedMap<String, String> httpHeaders, Object object, String key,
        String prefix) {
    try {
        String property = StringUtils.removeStart(key, prefix);
        Field field = object.getClass().getDeclaredField(StringUtils.uncapitalize(property));

        field.setAccessible(true);
        if (field.getType() == String.class) {
            field.set(object, httpHeaders.getFirst(key));
        } else if (field.getType() == int.class) {
            field.setInt(object, Integer.parseInt(httpHeaders.getFirst(key)));
        } else if (field.getType() == double.class) {
            field.setDouble(object, Double.parseDouble(httpHeaders.getFirst(key)));
        } else if (field.getType() == boolean.class) {
            field.setBoolean(object, Boolean.parseBoolean(httpHeaders.getFirst(key)));
        } else {
            //couldn't find a directly accessible field
            //try for setX(String s)
            String setter = StringUtils.uncapitalize(property);
            setter = "set" + setter.substring(0, 1).toUpperCase(Locale.US) + setter.substring(1);
            Method m = null;
            try {
                m = object.getClass().getMethod(setter, String.class);
            } catch (NoSuchMethodException e) {
                //swallow
            }
            if (m != null) {
                m.invoke(object, httpHeaders.getFirst(key));
            }
        }
    } catch (Throwable ex) {
        throw new WebApplicationException(
                String.format(Locale.ROOT, "%s is an invalid %s header", key, X_TIKA_OCR_HEADER_PREFIX));
    }
}

From source file:org.apache.tomcat.maven.plugin.tomcat7.run.AbstractExecWarMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (this.skip) {
        getLog().info("skip execution");
        return;//from  www.  j  a v  a 2 s .  c  o m
    }
    //project.addAttachedArtifact(  );
    File warExecFile = new File(buildDirectory, finalName);
    if (warExecFile.exists()) {
        warExecFile.delete();
    }

    File execWarJar = new File(buildDirectory, finalName);

    FileOutputStream execWarJarOutputStream = null;
    ArchiveOutputStream os = null;
    File tmpPropertiesFile = null;
    File tmpManifestFile = null;
    FileOutputStream tmpPropertiesFileOutputStream = null;
    PrintWriter tmpManifestWriter = null;

    try {

        tmpPropertiesFile = new File(buildDirectory, "war-exec.properties");
        if (tmpPropertiesFile.exists()) {
            tmpPropertiesFile.delete();
        }
        tmpPropertiesFile.getParentFile().mkdirs();

        tmpManifestFile = new File(buildDirectory, "war-exec.manifest");
        if (tmpManifestFile.exists()) {
            tmpManifestFile.delete();
        }
        tmpPropertiesFileOutputStream = new FileOutputStream(tmpPropertiesFile);
        execWarJar.getParentFile().mkdirs();
        execWarJar.createNewFile();
        execWarJarOutputStream = new FileOutputStream(execWarJar);

        tmpManifestWriter = new PrintWriter(tmpManifestFile);

        // store :
        //* wars in the root: foo.war
        //* tomcat jars
        //* file tomcat.standalone.properties with possible values :
        //   * useServerXml=true/false to use directly the one provided
        //   * enableNaming=true/false
        //   * wars=foo.war|contextpath;bar.war  ( |contextpath is optionnal if empty use the war name )
        //   * accessLogValveFormat=
        //   * connectorhttpProtocol: HTTP/1.1 or org.apache.coyote.http11.Http11NioProtocol
        //* optionnal: conf/ with usual tomcat configuration files
        //* MANIFEST with Main-Class

        Properties properties = new Properties();

        properties.put(Tomcat7Runner.ARCHIVE_GENERATION_TIMESTAMP_KEY,
                Long.toString(System.currentTimeMillis()));
        properties.put(Tomcat7Runner.ENABLE_NAMING_KEY, Boolean.toString(enableNaming));
        properties.put(Tomcat7Runner.ACCESS_LOG_VALVE_FORMAT_KEY, accessLogValveFormat);
        properties.put(Tomcat7Runner.HTTP_PROTOCOL_KEY, connectorHttpProtocol);

        if (httpPort != null) {
            properties.put(Tomcat7Runner.HTTP_PORT_KEY, httpPort);
        }

        os = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.JAR,
                execWarJarOutputStream);

        if ("war".equals(project.getPackaging())) {

            os.putArchiveEntry(new JarArchiveEntry(StringUtils.removeStart(path, "/") + ".war"));
            IOUtils.copy(new FileInputStream(projectArtifact.getFile()), os);
            os.closeArchiveEntry();

            properties.put(Tomcat7Runner.WARS_KEY, StringUtils.removeStart(path, "/") + ".war|" + path);
        } else if (warRunDependencies != null && !warRunDependencies.isEmpty()) {
            for (WarRunDependency warRunDependency : warRunDependencies) {
                if (warRunDependency.dependency != null) {
                    Dependency dependency = warRunDependency.dependency;
                    String version = dependency.getVersion();
                    if (StringUtils.isEmpty(version)) {
                        version = findArtifactVersion(dependency);
                    }

                    if (StringUtils.isEmpty(version)) {
                        throw new MojoExecutionException("Dependency '" + dependency.getGroupId() + "':'"
                                + dependency.getArtifactId() + "' does not have version specified");
                    }
                    Artifact artifact = artifactFactory.createArtifactWithClassifier(dependency.getGroupId(),
                            dependency.getArtifactId(), version, dependency.getType(),
                            dependency.getClassifier());

                    artifactResolver.resolve(artifact, this.remoteRepos, this.local);

                    File warFileToBundle = new File(resolvePluginWorkDir(), artifact.getFile().getName());
                    FileUtils.copyFile(artifact.getFile(), warFileToBundle);

                    if (warRunDependency.contextXml != null) {
                        warFileToBundle = addContextXmlToWar(warRunDependency.contextXml, warFileToBundle);
                    }
                    final String warFileName = artifact.getFile().getName();
                    os.putArchiveEntry(new JarArchiveEntry(warFileName));
                    IOUtils.copy(new FileInputStream(warFileToBundle), os);
                    os.closeArchiveEntry();
                    String propertyWarValue = properties.getProperty(Tomcat7Runner.WARS_KEY);
                    String contextPath = StringUtils.isEmpty(warRunDependency.contextPath) ? "/"
                            : warRunDependency.contextPath;
                    if (propertyWarValue != null) {
                        properties.put(Tomcat7Runner.WARS_KEY,
                                propertyWarValue + ";" + warFileName + "|" + contextPath);
                    } else {
                        properties.put(Tomcat7Runner.WARS_KEY, warFileName + "|" + contextPath);
                    }
                }
            }
        }

        if (serverXml != null && serverXml.exists()) {
            os.putArchiveEntry(new JarArchiveEntry("conf/server.xml"));
            IOUtils.copy(new FileInputStream(serverXml), os);
            os.closeArchiveEntry();
            properties.put(Tomcat7Runner.USE_SERVER_XML_KEY, Boolean.TRUE.toString());
        } else {
            properties.put(Tomcat7Runner.USE_SERVER_XML_KEY, Boolean.FALSE.toString());
        }

        os.putArchiveEntry(new JarArchiveEntry("conf/web.xml"));
        IOUtils.copy(getClass().getResourceAsStream("/conf/web.xml"), os);
        os.closeArchiveEntry();

        properties.store(tmpPropertiesFileOutputStream, "created by Apache Tomcat Maven plugin");

        tmpPropertiesFileOutputStream.flush();
        tmpPropertiesFileOutputStream.close();

        os.putArchiveEntry(new JarArchiveEntry(Tomcat7RunnerCli.STAND_ALONE_PROPERTIES_FILENAME));
        IOUtils.copy(new FileInputStream(tmpPropertiesFile), os);
        os.closeArchiveEntry();

        // add tomcat classes
        for (Artifact pluginArtifact : pluginArtifacts) {
            if (StringUtils.equals("org.apache.tomcat", pluginArtifact.getGroupId())
                    || StringUtils.equals("org.apache.tomcat.embed", pluginArtifact.getGroupId())
                    || StringUtils.equals("org.eclipse.jdt.core.compiler", pluginArtifact.getGroupId())
                    || StringUtils.equals("commons-cli", pluginArtifact.getArtifactId())
                    || StringUtils.equals("tomcat7-war-runner", pluginArtifact.getArtifactId())) {
                JarFile jarFile = new JarFile(pluginArtifact.getFile());
                extractJarToArchive(jarFile, os, null);
            }
        }

        // add extra dependencies
        if (extraDependencies != null && !extraDependencies.isEmpty()) {
            for (Dependency dependency : extraDependencies) {
                String version = dependency.getVersion();
                if (StringUtils.isEmpty(version)) {
                    version = findArtifactVersion(dependency);
                }

                if (StringUtils.isEmpty(version)) {
                    throw new MojoExecutionException("Dependency '" + dependency.getGroupId() + "':'"
                            + dependency.getArtifactId() + "' does not have version specified");
                }

                // String groupId, String artifactId, String version, String scope, String type
                Artifact artifact = artifactFactory.createArtifact(dependency.getGroupId(),
                        dependency.getArtifactId(), version, dependency.getScope(), dependency.getType());

                artifactResolver.resolve(artifact, this.remoteRepos, this.local);
                JarFile jarFile = new JarFile(artifact.getFile());
                extractJarToArchive(jarFile, os, this.excludes);
            }
        }

        Manifest manifest = new Manifest();

        Manifest.Attribute mainClassAtt = new Manifest.Attribute();
        mainClassAtt.setName("Main-Class");
        mainClassAtt.setValue(mainClass);
        manifest.addConfiguredAttribute(mainClassAtt);

        manifest.write(tmpManifestWriter);
        tmpManifestWriter.flush();
        tmpManifestWriter.close();

        os.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF"));
        IOUtils.copy(new FileInputStream(tmpManifestFile), os);
        os.closeArchiveEntry();

        if (attachArtifact) {
            //MavenProject project, String artifactType, String artifactClassifier, File artifactFile
            projectHelper.attachArtifact(project, attachArtifactClassifierType, attachArtifactClassifier,
                    execWarJar);
        }

        if (extraResources != null) {
            for (ExtraResource extraResource : extraResources) {

                DirectoryScanner directoryScanner = new DirectoryScanner();
                directoryScanner.setBasedir(extraResource.getDirectory());
                directoryScanner.addDefaultExcludes();
                directoryScanner.setExcludes(toStringArray(extraResource.getExcludes()));
                directoryScanner.setIncludes(toStringArray(extraResource.getIncludes()));
                directoryScanner.scan();
                for (String includeFile : directoryScanner.getIncludedFiles()) {
                    getLog().debug("include file:" + includeFile);
                    os.putArchiveEntry(new JarArchiveEntry(includeFile));
                    IOUtils.copy(new FileInputStream(new File(extraResource.getDirectory(), includeFile)), os);
                    os.closeArchiveEntry();
                }
            }
        }

        if (tomcatConfigurationFilesDirectory != null && tomcatConfigurationFilesDirectory.exists()) {
            // Because its the tomcat default dir for configs
            String aConfigOutputDir = "conf/";
            copyDirectoryContentIntoArchive(tomcatConfigurationFilesDirectory, aConfigOutputDir, os);
        }

    } catch (ManifestException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (ArchiveException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (ArtifactNotFoundException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(tmpManifestWriter);
        IOUtils.closeQuietly(execWarJarOutputStream);
        IOUtils.closeQuietly(tmpPropertiesFileOutputStream);
    }
}

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

public void execute() throws MojoExecutionException, MojoFailureException {
    if (this.skip) {
        getLog().info("skip execution");
        return;/*from  w ww .  j av  a  2  s .  c om*/
    }
    //project.addAttachedArtifact(  );
    File warExecFile = new File(buildDirectory, finalName);
    if (warExecFile.exists()) {
        warExecFile.delete();
    }

    File execWarJar = new File(buildDirectory, finalName);

    FileOutputStream execWarJarOutputStream = null;
    ArchiveOutputStream os = null;
    File tmpPropertiesFile = null;
    File tmpManifestFile = null;
    FileOutputStream tmpPropertiesFileOutputStream = null;
    PrintWriter tmpManifestWriter = null;

    try {

        tmpPropertiesFile = new File(buildDirectory, "war-exec.properties");
        if (tmpPropertiesFile.exists()) {
            tmpPropertiesFile.delete();
        }
        tmpPropertiesFile.getParentFile().mkdirs();

        tmpManifestFile = new File(buildDirectory, "war-exec.manifest");
        if (tmpManifestFile.exists()) {
            tmpManifestFile.delete();
        }
        tmpPropertiesFileOutputStream = new FileOutputStream(tmpPropertiesFile);
        execWarJar.getParentFile().mkdirs();
        execWarJar.createNewFile();
        execWarJarOutputStream = new FileOutputStream(execWarJar);

        tmpManifestWriter = new PrintWriter(tmpManifestFile);

        // store :
        //* wars in the root: foo.war
        //* tomcat jars
        //* file tomcat.standalone.properties with possible values :
        //   * useServerXml=true/false to use directly the one provided
        //   * enableNaming=true/false
        //   * wars=foo.war|contextpath;bar.war  ( |contextpath is optionnal if empty use the war name )
        //   * accessLogValveFormat=
        //   * connectorhttpProtocol: HTTP/1.1 or org.apache.coyote.http11.Http11NioProtocol
        //* optionnal: conf/ with usual tomcat configuration files
        //* MANIFEST with Main-Class

        Properties properties = new Properties();

        properties.put(Tomcat8Runner.ARCHIVE_GENERATION_TIMESTAMP_KEY,
                Long.toString(System.currentTimeMillis()));
        properties.put(Tomcat8Runner.ENABLE_NAMING_KEY, Boolean.toString(enableNaming));
        properties.put(Tomcat8Runner.ACCESS_LOG_VALVE_FORMAT_KEY, accessLogValveFormat);
        properties.put(Tomcat8Runner.HTTP_PROTOCOL_KEY, connectorHttpProtocol);

        if (httpPort != null) {
            properties.put(Tomcat8Runner.HTTP_PORT_KEY, httpPort);
        }

        os = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.JAR,
                execWarJarOutputStream);

        if ("war".equals(project.getPackaging())) {

            os.putArchiveEntry(new JarArchiveEntry(StringUtils.removeStart(path, "/") + ".war"));
            IOUtils.copy(new FileInputStream(projectArtifact.getFile()), os);
            os.closeArchiveEntry();

            properties.put(Tomcat8Runner.WARS_KEY, StringUtils.removeStart(path, "/") + ".war|" + path);
        } else if (warRunDependencies != null && !warRunDependencies.isEmpty()) {
            for (WarRunDependency warRunDependency : warRunDependencies) {
                if (warRunDependency.dependency != null) {
                    Dependency dependency = warRunDependency.dependency;
                    String version = dependency.getVersion();
                    if (StringUtils.isEmpty(version)) {
                        version = findArtifactVersion(dependency);
                    }

                    if (StringUtils.isEmpty(version)) {
                        throw new MojoExecutionException("Dependency '" + dependency.getGroupId() + "':'"
                                + dependency.getArtifactId() + "' does not have version specified");
                    }
                    Artifact artifact = artifactFactory.createArtifactWithClassifier(dependency.getGroupId(), //
                            dependency.getArtifactId(), //
                            version, //
                            dependency.getType(), //
                            dependency.getClassifier());

                    artifactResolver.resolve(artifact, this.remoteRepos, this.local);

                    File warFileToBundle = new File(resolvePluginWorkDir(), artifact.getFile().getName());
                    FileUtils.copyFile(artifact.getFile(), warFileToBundle);

                    if (warRunDependency.contextXml != null) {
                        warFileToBundle = addContextXmlToWar(warRunDependency.contextXml, warFileToBundle);
                    }
                    final String warFileName = artifact.getFile().getName();
                    os.putArchiveEntry(new JarArchiveEntry(warFileName));
                    IOUtils.copy(new FileInputStream(warFileToBundle), os);
                    os.closeArchiveEntry();
                    String propertyWarValue = properties.getProperty(Tomcat8Runner.WARS_KEY);
                    String contextPath = StringUtils.isEmpty(warRunDependency.contextPath) ? "/"
                            : warRunDependency.contextPath;
                    if (propertyWarValue != null) {
                        properties.put(Tomcat8Runner.WARS_KEY,
                                propertyWarValue + ";" + warFileName + "|" + contextPath);
                    } else {
                        properties.put(Tomcat8Runner.WARS_KEY, warFileName + "|" + contextPath);
                    }
                }
            }
        }

        if (serverXml != null && serverXml.exists()) {
            os.putArchiveEntry(new JarArchiveEntry("conf/server.xml"));
            IOUtils.copy(new FileInputStream(serverXml), os);
            os.closeArchiveEntry();
            properties.put(Tomcat8Runner.USE_SERVER_XML_KEY, Boolean.TRUE.toString());
        } else {
            properties.put(Tomcat8Runner.USE_SERVER_XML_KEY, Boolean.FALSE.toString());
        }

        os.putArchiveEntry(new JarArchiveEntry("conf/web.xml"));
        IOUtils.copy(getClass().getResourceAsStream("/conf/web.xml"), os);
        os.closeArchiveEntry();

        properties.store(tmpPropertiesFileOutputStream, "created by Apache Tomcat Maven plugin");

        tmpPropertiesFileOutputStream.flush();
        tmpPropertiesFileOutputStream.close();

        os.putArchiveEntry(new JarArchiveEntry(Tomcat8RunnerCli.STAND_ALONE_PROPERTIES_FILENAME));
        IOUtils.copy(new FileInputStream(tmpPropertiesFile), os);
        os.closeArchiveEntry();

        // add tomcat classes
        for (Artifact pluginArtifact : pluginArtifacts) {
            if (StringUtils.equals("org.apache.tomcat", pluginArtifact.getGroupId()) //
                    || StringUtils.equals("org.apache.tomcat.embed", pluginArtifact.getGroupId()) //
                    || StringUtils.equals("org.eclipse.jdt.core.compiler", pluginArtifact.getGroupId()) //
                    || StringUtils.equals("commons-cli", pluginArtifact.getArtifactId()) //
                    || StringUtils.equals("tomcat8-war-runner", pluginArtifact.getArtifactId())) {
                JarFile jarFile = new JarFile(pluginArtifact.getFile());
                extractJarToArchive(jarFile, os, null);
            }
        }

        // add extra dependencies
        if (extraDependencies != null && !extraDependencies.isEmpty()) {
            for (Dependency dependency : extraDependencies) {
                String version = dependency.getVersion();
                if (StringUtils.isEmpty(version)) {
                    version = findArtifactVersion(dependency);
                }

                if (StringUtils.isEmpty(version)) {
                    throw new MojoExecutionException("Dependency '" + dependency.getGroupId() + "':'"
                            + dependency.getArtifactId() + "' does not have version specified");
                }

                // String groupId, String artifactId, String version, String scope, String type
                Artifact artifact = artifactFactory.createArtifact(dependency.getGroupId(), //
                        dependency.getArtifactId(), //
                        version, //
                        dependency.getScope(), //
                        dependency.getType());

                artifactResolver.resolve(artifact, this.remoteRepos, this.local);
                JarFile jarFile = new JarFile(artifact.getFile());
                extractJarToArchive(jarFile, os, this.excludes);
            }
        }

        Manifest manifest = new Manifest();

        Manifest.Attribute mainClassAtt = new Manifest.Attribute();
        mainClassAtt.setName("Main-Class");
        mainClassAtt.setValue(mainClass);
        manifest.addConfiguredAttribute(mainClassAtt);

        manifest.write(tmpManifestWriter);
        tmpManifestWriter.flush();
        tmpManifestWriter.close();

        os.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF"));
        IOUtils.copy(new FileInputStream(tmpManifestFile), os);
        os.closeArchiveEntry();

        if (attachArtifact) {
            //MavenProject project, String artifactType, String artifactClassifier, File artifactFile
            projectHelper.attachArtifact(project, attachArtifactClassifierType, attachArtifactClassifier,
                    execWarJar);
        }

        if (extraResources != null) {
            for (ExtraResource extraResource : extraResources) {

                DirectoryScanner directoryScanner = new DirectoryScanner();
                directoryScanner.setBasedir(extraResource.getDirectory());
                directoryScanner.addDefaultExcludes();
                directoryScanner.setExcludes(toStringArray(extraResource.getExcludes()));
                directoryScanner.setIncludes(toStringArray(extraResource.getIncludes()));
                directoryScanner.scan();
                for (String includeFile : directoryScanner.getIncludedFiles()) {
                    getLog().debug("include file:" + includeFile);
                    os.putArchiveEntry(new JarArchiveEntry(includeFile));
                    IOUtils.copy(new FileInputStream(new File(extraResource.getDirectory(), includeFile)), os);
                    os.closeArchiveEntry();
                }
            }
        }

        if (tomcatConfigurationFilesDirectory != null && tomcatConfigurationFilesDirectory.exists()) {
            // Because its the tomcat default dir for configs
            String aConfigOutputDir = "conf/";
            copyDirectoryContentIntoArchive(tomcatConfigurationFilesDirectory, aConfigOutputDir, os);
        }

    } catch (ManifestException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (ArchiveException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (ArtifactNotFoundException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(tmpManifestWriter);
        IOUtils.closeQuietly(execWarJarOutputStream);
        IOUtils.closeQuietly(tmpPropertiesFileOutputStream);
    }
}

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 {/*from w  w  w. ja  v a  2 s.  co  m*/
        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.artifactory.descriptor.repo.HttpRepoDescriptor.java

public String getQueryParams() {
    return StringUtils.removeStart(queryParams, "?");
}

From source file:org.artifactory.repo.remote.browse.S3RepositoryBrowser.java

private String buildS3RequestUrl(String url) {
    url = forceDirectoryUrl(url);/*from   w ww . ja v a 2 s. co  m*/
    if (secured) {
        String pfx = getPrefix(url);
        return buildSecuredS3RequestUrl(url, httpRepo, "") + "&prefix=" + pfx + "&delimiter=/";
    }
    // the s3 request should always go to the root and add the rest of the path as the prefix parameter.
    String prefixPath = StringUtils.removeStart(url, rootUrl);
    StringBuilder sb = new StringBuilder(rootUrl).append("?prefix=").append(prefixPath);

    // we assume a file system structure with '/' as the delimiter
    sb.append("&").append("delimiter=/");
    return HttpUtils.encodeQuery(sb.toString());
}

From source file:org.artifactory.repo.remote.browse.S3RepositoryBrowser.java

@SuppressWarnings({ "unchecked" })
private List<RemoteItem> parseResponse(String content) {
    List<RemoteItem> items = Lists.newArrayList();
    Document document = XmlUtils.parse(content);
    Element root = document.getRootElement();
    Namespace ns = root.getNamespace();
    String prefix = root.getChildText("Prefix", ns);

    // retrieve folders
    List<Element> folders = root.getChildren("CommonPrefixes", ns);
    for (Element folder : folders) {
        String directoryPath = folder.getChildText("Prefix", ns);
        String folderName = StringUtils.removeStart(directoryPath, prefix);
        if (StringUtils.isNotBlank(folderName)) {
            if (secured) {
                directoryPath = StringUtils.removeStart(directoryPath, getPrefix(rootUrl));
            }/* w ww .j  a  v  a2  s .  c om*/
            items.add(new RemoteItem(rootUrl + directoryPath, true));
        }
    }

    // retrieve files
    List<Element> files = root.getChildren("Contents", ns);
    for (Element element : files) {
        String filePath = element.getChildText("Key", ns);
        String fileName = StringUtils.removeStart(filePath, prefix);
        if (StringUtils.isNotBlank(fileName) && !folderDirectoryWithSameNameExists(fileName, items)) {
            // the date format is of the form yyyy-mm-ddThh:mm:ss.timezone, e.g., 2009-02-03T16:45:09.000Z
            String sizeStr = element.getChildText("Size", ns);
            long size = sizeStr == null ? 0 : Long.parseLong(sizeStr);
            String lastModifiedStr = element.getChildText("LastModified", ns);
            long lastModified = lastModifiedStr == null ? 0
                    : ISODateTimeFormat.dateTime().parseMillis(lastModifiedStr);
            if (secured) {
                RemoteItem remoteItem = new RemoteItem(rootUrl + filePath, false, size, lastModified);
                String filePath2 = StringUtils.removeStart(filePath, getPrefix(rootUrl));
                String url = rootUrl + filePath2;
                String securedPath = buildSecuredS3RequestUrl(url, httpRepo, getPrefix(url));
                remoteItem.setEffectiveUrl(securedPath);
                items.add(remoteItem);
            } else {
                items.add(new RemoteItem(rootUrl + filePath, false, size, lastModified));
            }
        }
    }

    return items;
}

From source file:org.artifactory.repo.service.RepositoryBrowsingServiceImpl.java

private void listRemoteBrowsableChildren(List<BaseBrowsableItem> children, RemoteRepo repo, String relativePath,
        boolean pathExistsInCache, boolean updateRootNodesFilterFlag,
        RootNodesFilterResult rootNodesFilterResult) {
    RepoPath repoPath = repo.getRepoPath(relativePath);
    List<RemoteItem> remoteItems = repo.listRemoteResources(relativePath);
    // probably remote not found - return 404 only if current folder doesn't exist in the cache
    if (remoteItems.isEmpty() && !pathExistsInCache) {
        // no cache and remote failed - signal 404
        log.trace("Couldn't find item:'{}'", repoPath);
        throw new ItemNotFoundRuntimeException("Couldn't find item: " + repoPath);
    }/*  w w  w. j a va  2s  .  c o  m*/
    log.debug("Listing Remote Repo '{}' Browsable Items", repoPath.getRepoKey());

    // filter already existing local items
    remoteItems = Lists
            .newArrayList(Iterables.filter(remoteItems, new RemoteOnlyBrowsableItemPredicate(children)));
    for (RemoteItem remoteItem : remoteItems) {
        // remove the remote repository base url
        String path = StringUtils.removeStart(remoteItem.getUrl(), removeBaseUrl(repo.getUrl()));
        RepoPath remoteRepoPath = InternalRepoPathFactory.create(repoPath.getRepoKey(), path,
                remoteItem.isDirectory());
        RepoPath cacheRepoPath = InternalRepoPathFactory.cacheRepoPath(remoteRepoPath);
        if (canRead(repo, cacheRepoPath)) {
            RemoteBrowsableItem browsableItem = new RemoteBrowsableItem(remoteItem, remoteRepoPath);
            if (remoteItem.getEffectiveUrl() != null) {
                log.debug("Remote Browsable item effective URL", remoteItem.getEffectiveUrl());
                browsableItem.setEffectiveUrl(remoteItem.getEffectiveUrl());
            }
            children.add(browsableItem);
        } else if (updateRootNodesFilterFlag && !authService.canRead(cacheRepoPath)) {
            rootNodesFilterResult.setAllItemNodesCanRead(false);
        }
    }
    if (updateRootNodesFilterFlag && !children.isEmpty()) {
        rootNodesFilterResult.setAllItemNodesCanRead(true);
    }
}