Example usage for java.util.jar JarEntry getName

List of usage examples for java.util.jar JarEntry getName

Introduction

In this page you can find the example usage for java.util.jar JarEntry getName.

Prototype

public String getName() 

Source Link

Document

Returns the name of the entry.

Usage

From source file:org.apache.storm.utils.Utils.java

public static Map<String, Object> getConfigFromClasspath(List<String> cp, Map<String, Object> conf)
        throws IOException {
    if (cp == null || cp.isEmpty()) {
        return conf;
    }/*from   w w w. j av  a  2 s  .c om*/
    Yaml yaml = new Yaml(new SafeConstructor());
    Map<String, Object> defaultsConf = null;
    Map<String, Object> stormConf = null;
    for (String part : cp) {
        File f = new File(part);
        if (f.isDirectory()) {
            if (defaultsConf == null) {
                defaultsConf = readConfIgnoreNotFound(yaml, new File(f, "defaults.yaml"));
            }

            if (stormConf == null) {
                stormConf = readConfIgnoreNotFound(yaml, new File(f, "storm.yaml"));
            }
        } else {
            //Lets assume it is a jar file
            try (JarFile jarFile = new JarFile(f)) {
                Enumeration<JarEntry> jarEnums = jarFile.entries();
                while (jarEnums.hasMoreElements()) {
                    JarEntry entry = jarEnums.nextElement();
                    if (!entry.isDirectory()) {
                        if (defaultsConf == null && entry.getName().equals("defaults.yaml")) {
                            try (InputStream in = jarFile.getInputStream(entry)) {
                                defaultsConf = (Map<String, Object>) yaml.load(new InputStreamReader(in));
                            }
                        }

                        if (stormConf == null && entry.getName().equals("storm.yaml")) {
                            try (InputStream in = jarFile.getInputStream(entry)) {
                                stormConf = (Map<String, Object>) yaml.load(new InputStreamReader(in));
                            }
                        }
                    }
                }
            }
        }
    }
    if (stormConf != null) {
        defaultsConf.putAll(stormConf);
    }
    return defaultsConf;
}

From source file:org.apache.struts2.convention.DefaultClassFinder.java

private List<String> jar(JarInputStream jarStream) throws IOException {
    List<String> classNames = new ArrayList<>();

    JarEntry entry;
    while ((entry = jarStream.getNextJarEntry()) != null) {
        if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
            continue;
        }//from w ww .  j av  a2s  .  c  om
        String className = entry.getName();
        className = className.replaceFirst(".class$", "");

        //war files are treated as .jar files, so takeout WEB-INF/classes
        className = StringUtils.removeStart(className, "WEB-INF/classes/");

        className = className.replace('/', '.');
        classNames.add(className);
    }

    return classNames;
}

From source file:lineage2.gameserver.scripts.Scripts.java

/**
 * Method load./*from ww w .  j  av a 2s. com*/
 */
private void load() {
    _log.info("Scripts: Loading...");

    List<Class<?>> classes = new ArrayList<>();

    boolean result = false;

    File f = new File("../libs/lineage2-scripts.jar");
    if (f.exists()) {
        JarInputStream stream = null;
        try {
            stream = new JarInputStream(new FileInputStream(f));
            JarEntry entry = null;
            while ((entry = stream.getNextJarEntry()) != null) {
                if (entry.getName().contains(ClassUtils.INNER_CLASS_SEPARATOR)
                        || !entry.getName().endsWith(".class")) {
                    continue;
                }

                String name = entry.getName().replace(".class", "").replace("/", ".");

                Class<?> clazz = Class.forName(name);
                if (Modifier.isAbstract(clazz.getModifiers())) {
                    continue;
                }
                classes.add(clazz);
            }
            result = true;
        } catch (Exception e) {
            _log.error("Fail to load scripts.jar!", e);
            classes.clear();
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    if (!result) {
        result = load(classes, "");
    }

    if (!result) {
        _log.error("Scripts: Failed loading scripts!");
        Runtime.getRuntime().exit(0);
        return;
    }

    _log.info("Scripts: Loaded " + classes.size() + " classes.");

    Class<?> clazz;
    for (int i = 0; i < classes.size(); i++) {
        clazz = classes.get(i);
        _classes.put(clazz.getName(), clazz);
    }
}

From source file:org.jasig.portal.plugin.deployer.AbstractExtractingEarDeployer.java

/**
 * Reads the specified {@link JarEntry} from the {@link JarFile} assuming that the
 * entry represents another a JAR file. The files in the {@link JarEntry} will be
 * extracted using the contextDir as the base directory. 
 * //from w  w w. j a v a2  s . c  o  m
 * @param earFile The JarEntry for the JAR to read from the archive.
 * @param earEntry The JarFile to get the {@link InputStream} for the file from.
 * @param contextDir The directory to extract the JAR to.
 * @throws IOException If the extracting of data from the JarEntry fails.
 */
protected void extractWar(JarFile earFile, final JarEntry earEntry, final File contextDir)
        throws MojoFailureException {
    if (this.getLogger().isInfoEnabled()) {
        this.getLogger().info("Extracting EAR entry '" + earFile.getName() + "!" + earEntry.getName() + "' to '"
                + contextDir + "'");
    }

    if (!contextDir.exists()) {
        if (this.getLogger().isDebugEnabled()) {
            this.getLogger().debug("Creating context directory entry '" + contextDir + "'");
        }

        try {
            FileUtils.forceMkdir(contextDir);
        } catch (IOException e) {
            throw new MojoFailureException("Failed to create '" + contextDir + "' to extract '"
                    + earEntry.getName() + "' out of '" + earFile.getName() + "' into", e);
        }
    }

    JarInputStream warInputStream = null;
    try {
        warInputStream = new JarInputStream(earFile.getInputStream(earEntry));

        // Write out the MANIFEST.MF file to the target directory
        Manifest manifest = warInputStream.getManifest();
        if (manifest != null) {
            FileOutputStream manifestFileOutputStream = null;
            try {
                final File manifestFile = new File(contextDir, MANIFEST_PATH);
                manifestFile.getParentFile().mkdirs();
                manifestFileOutputStream = new FileOutputStream(manifestFile);
                manifest.write(manifestFileOutputStream);
            } catch (Exception e) {
                this.getLogger().error("Failed to copy the MANIFEST.MF file for ear entry '"
                        + earEntry.getName() + "' out of '" + earFile.getName() + "'", e);
                throw new MojoFailureException("Failed to copy the MANIFEST.MF file for ear entry '"
                        + earEntry.getName() + "' out of '" + earFile.getName() + "'", e);
            } finally {
                try {
                    if (manifestFileOutputStream != null) {
                        manifestFileOutputStream.close();
                    }
                } catch (Exception e) {
                    this.getLogger().warn("Error closing the OutputStream for MANIFEST.MF in warEntry:  "
                            + earEntry.getName());
                }
            }
        }

        JarEntry warEntry;
        while ((warEntry = warInputStream.getNextJarEntry()) != null) {
            final File warEntryFile = new File(contextDir, warEntry.getName());

            if (warEntry.isDirectory()) {
                if (this.getLogger().isDebugEnabled()) {
                    this.getLogger().debug("Creating WAR directory entry '" + earEntry.getName() + "!"
                            + warEntry.getName() + "' as '" + warEntryFile + "'");
                }

                FileUtils.forceMkdir(warEntryFile);
            } else {
                if (this.getLogger().isDebugEnabled()) {
                    this.getLogger().debug("Extracting WAR entry '" + earEntry.getName() + "!"
                            + warEntry.getName() + "' to '" + warEntryFile + "'");
                }

                FileUtils.forceMkdir(warEntryFile.getParentFile());

                final FileOutputStream jarEntryFileOutputStream = new FileOutputStream(warEntryFile);
                try {
                    IOUtils.copy(warInputStream, jarEntryFileOutputStream);
                } finally {
                    IOUtils.closeQuietly(jarEntryFileOutputStream);
                }
            }
        }
    } catch (IOException e) {
        throw new MojoFailureException("Failed to extract EAR entry '" + earEntry.getName() + "' out of '"
                + earFile.getName() + "' to '" + contextDir + "'", e);
    } finally {
        IOUtils.closeQuietly(warInputStream);
    }
}

From source file:com.slamd.admin.JobPack.java

/**
 * Extracts the contents of the job pack and registers the included jobs with
 * the SLAMD server.// ww  w.  j  a  v a  2s .c  o m
 *
 * @throws  SLAMDServerException  If a problem occurs while processing the job
 *                                pack JAR file.
 */
public void processJobPack() throws SLAMDServerException {
    byte[] fileData = null;
    File tempFile = null;
    String fileName = null;
    String separator = System.getProperty("file.separator");

    if (filePath == null) {
        // First, get the request and ensure it is multipart content.
        HttpServletRequest request = requestInfo.request;
        if (!FileUpload.isMultipartContent(request)) {
            throw new SLAMDServerException("Request does not contain multipart " + "content");
        }

        // Iterate through the request fields to get to the file data.
        Iterator iterator = fieldList.iterator();
        while (iterator.hasNext()) {
            FileItem fileItem = (FileItem) iterator.next();
            String fieldName = fileItem.getFieldName();

            if (fieldName.equals(Constants.SERVLET_PARAM_JOB_PACK_FILE)) {
                fileData = fileItem.get();
                fileName = fileItem.getName();
            }
        }

        // Make sure that a file was actually uploaded.
        if (fileData == null) {
            throw new SLAMDServerException("No file data was found in the " + "request.");
        }

        // Write the JAR file data to a temp file, since that's the only way we
        // can parse it.
        if (separator == null) {
            separator = "/";
        }

        tempFile = new File(jobClassDirectory + separator + fileName);
        try {
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            outputStream.write(fileData);
            outputStream.flush();
            outputStream.close();
        } catch (IOException ioe) {
            try {
                tempFile.delete();
            } catch (Exception e) {
            }

            ioe.printStackTrace();
            slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
            throw new SLAMDServerException("I/O error writing temporary JAR " + "file:  " + ioe, ioe);
        }
    } else {
        tempFile = new File(filePath);
        if ((!tempFile.exists()) || (!tempFile.isFile())) {
            throw new SLAMDServerException("Specified job pack file \"" + filePath + "\" does not exist");
        }

        try {
            fileName = tempFile.getName();
            int fileLength = (int) tempFile.length();
            fileData = new byte[fileLength];

            FileInputStream inputStream = new FileInputStream(tempFile);
            int bytesRead = 0;
            while (bytesRead < fileLength) {
                bytesRead += inputStream.read(fileData, bytesRead, fileLength - bytesRead);
            }
            inputStream.close();
        } catch (Exception e) {
            slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e));
            throw new SLAMDServerException("Error reading job pack file \"" + filePath + "\" -- " + e, e);
        }
    }

    StringBuilder htmlBody = requestInfo.htmlBody;

    // Parse the jar file
    JarFile jarFile = null;
    Manifest manifest = null;
    Enumeration jarEntries = null;
    try {
        jarFile = new JarFile(tempFile, true);
        manifest = jarFile.getManifest();
        jarEntries = jarFile.entries();
    } catch (IOException ioe) {
        try {
            if (filePath == null) {
                tempFile.delete();
            }
        } catch (Exception e) {
        }

        ioe.printStackTrace();
        slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
        throw new SLAMDServerException("Unable to parse the JAR file:  " + ioe, ioe);
    }

    ArrayList<String> dirList = new ArrayList<String>();
    ArrayList<String> fileNameList = new ArrayList<String>();
    ArrayList<byte[]> fileDataList = new ArrayList<byte[]>();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
        String entryName = jarEntry.getName();
        if (jarEntry.isDirectory()) {
            dirList.add(entryName);
        } else {
            try {
                int entrySize = (int) jarEntry.getSize();
                byte[] entryData = new byte[entrySize];
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                extractFileData(inputStream, entryData);
                fileNameList.add(entryName);
                fileDataList.add(entryData);
            } catch (IOException ioe) {
                try {
                    jarFile.close();
                    if (filePath == null) {
                        tempFile.delete();
                    }
                } catch (Exception e) {
                }

                ioe.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
                throw new SLAMDServerException("I/O error parsing JAR entry " + entryName + " -- " + ioe, ioe);
            } catch (SLAMDServerException sse) {
                try {
                    jarFile.close();
                    if (filePath == null) {
                        tempFile.delete();
                    }
                } catch (Exception e) {
                }

                sse.printStackTrace();
                throw sse;
            }
        }
    }

    // If we have gotten here, then we have read all the data from the JAR file.
    // Delete the temporary file to prevent possible (although unlikely)
    // conflicts with data contained in the JAR.
    try {
        jarFile.close();
        if (filePath == null) {
            tempFile.delete();
        }
    } catch (Exception e) {
    }

    // Create the directory structure specified in the JAR file.
    if (!dirList.isEmpty()) {
        htmlBody.append("<B>Created the following directories</B>" + Constants.EOL);
        htmlBody.append("<BR>" + Constants.EOL);
        htmlBody.append("<UL>" + Constants.EOL);

        for (int i = 0; i < dirList.size(); i++) {
            File dirFile = new File(jobClassDirectory + separator + dirList.get(i));
            try {
                dirFile.mkdirs();
                htmlBody.append("  <LI>" + dirFile.getAbsolutePath() + "</LI>" + Constants.EOL);
            } catch (Exception e) {
                htmlBody.append("</UL>" + Constants.EOL);
                e.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e));
                throw new SLAMDServerException(
                        "Unable to create directory \"" + dirFile.getAbsolutePath() + " -- " + e, e);
            }
        }

        htmlBody.append("</UL>" + Constants.EOL);
        htmlBody.append("<BR><BR>" + Constants.EOL);
    }

    // Write all the files to disk.  If we have gotten this far, then there
    // should not be any failures, but if there are, then we will have to
    // leave things in a "dirty" state.
    if (!fileNameList.isEmpty()) {
        htmlBody.append("<B>Created the following files</B>" + Constants.EOL);
        htmlBody.append("<BR>" + Constants.EOL);
        htmlBody.append("<UL>" + Constants.EOL);

        for (int i = 0; i < fileNameList.size(); i++) {
            File dataFile = new File(jobClassDirectory + separator + fileNameList.get(i));

            try {
                // Make sure the parent directory exists.
                dataFile.getParentFile().mkdirs();
            } catch (Exception e) {
            }

            try {
                FileOutputStream outputStream = new FileOutputStream(dataFile);
                outputStream.write(fileDataList.get(i));
                outputStream.flush();
                outputStream.close();
                htmlBody.append("  <LI>" + dataFile.getAbsolutePath() + "</LI>" + Constants.EOL);
            } catch (IOException ioe) {
                htmlBody.append("</UL>" + Constants.EOL);
                ioe.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
                throw new SLAMDServerException("Unable to write file " + dataFile.getAbsolutePath() + ioe, ioe);
            }
        }

        htmlBody.append("</UL>" + Constants.EOL);
        htmlBody.append("<BR><BR>" + Constants.EOL);
    }

    // Finally, parse the manifest to get the names of the classes that should
    // be registered with the SLAMD server.
    Attributes manifestAttributes = manifest.getMainAttributes();
    Attributes.Name key = new Attributes.Name(Constants.JOB_PACK_MANIFEST_REGISTER_JOBS_ATTR);
    String registerClassesStr = (String) manifestAttributes.get(key);
    if ((registerClassesStr == null) || (registerClassesStr.length() == 0)) {
        htmlBody.append("<B>No job classes registered</B>" + Constants.EOL);
    } else {
        ArrayList<String> successList = new ArrayList<String>();
        ArrayList<String> failureList = new ArrayList<String>();

        StringTokenizer tokenizer = new StringTokenizer(registerClassesStr, ", \t\r\n");
        while (tokenizer.hasMoreTokens()) {
            String className = tokenizer.nextToken();

            try {
                JobClass jobClass = slamdServer.loadJobClass(className);
                slamdServer.addJobClass(jobClass);
                successList.add(className);
            } catch (Exception e) {
                failureList.add(className + ":  " + e);
            }
        }

        if (!successList.isEmpty()) {
            htmlBody.append("<B>Registered Job Classes</B>" + Constants.EOL);
            htmlBody.append("<UL>" + Constants.EOL);
            for (int i = 0; i < successList.size(); i++) {
                htmlBody.append("  <LI>" + successList.get(i) + "</LI>" + Constants.EOL);
            }
            htmlBody.append("</UL>" + Constants.EOL);
            htmlBody.append("<BR><BR>" + Constants.EOL);
        }

        if (!failureList.isEmpty()) {
            htmlBody.append("<B>Unable to Register Job Classes</B>" + Constants.EOL);
            htmlBody.append("<UL>" + Constants.EOL);
            for (int i = 0; i < failureList.size(); i++) {
                htmlBody.append("  <LI>" + failureList.get(i) + "</LI>" + Constants.EOL);
            }
            htmlBody.append("</UL>" + Constants.EOL);
            htmlBody.append("<BR><BR>" + Constants.EOL);
        }
    }
}

From source file:org.ebayopensource.turmeric.tools.codegen.util.CodeGenClassLoader.java

public URL findResource(String resourceName) {
    for (URL url : m_jarURLs) {

        JarFile jarFile = null;/*from  w  w  w.j  av  a2  s .c o  m*/
        try {
            File file = CodeGenUtil.urlToFile(url);
            jarFile = new JarFile(file);
            JarEntry jarEntry = jarFile.getJarEntry(resourceName);
            if (jarEntry == null) {
                continue; // Skip, not part of this jar.
            }
            // Java supports "jar:" url references natively.
            return new URL(String.format("jar:%s!/%s", file.toURI().toASCIIString(), jarEntry.getName()));
        } catch (IOException e) {
            e.printStackTrace(); // KEEPME
        } catch (Exception e) {
            /* ignore */
        } finally {
            CodeGenUtil.closeQuietly(jarFile);
        }

    }
    return super.findResource(resourceName);
}

From source file:org.hyperic.hq.plugin.websphere.WebsphereProductPlugin.java

private File runtimeJarHack(File file) throws Exception {
    String tmp = System.getProperty("java.io.tmpdir"); //agent/tmp
    File newJar = new File(tmp, file.getName());
    if (newJar.exists()) {
        return newJar;
    }/*from  w w w  .j av a 2 s  . c om*/
    log.debug("Creating " + newJar);
    JarFile jar = new JarFile(file);
    JarOutputStream os = new JarOutputStream(new FileOutputStream(newJar));
    byte[] buffer = new byte[1024];
    try {
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            int n;
            JarEntry entry = e.nextElement();

            if (entry.getName().startsWith("org/apache/commons/logging/")) {
                continue;
            }
            InputStream entryStream = jar.getInputStream(entry);

            os.putNextEntry(entry);
            while ((n = entryStream.read(buffer)) != -1) {
                os.write(buffer, 0, n);
            }
            entryStream.close();
        }
    } finally {
        jar.close();
        os.close();
    }
    return newJar;
}

From source file:fr.gael.dhus.server.http.TomcatServer.java

public void install(WebApplication web_application) throws TomcatException {
    try {/*from w w  w . ja  va2  s .co  m*/
        String folder = web_application.getName() == "" ? "ROOT" : web_application.getName();
        if (web_application.hasWarStream()) {
            InputStream stream = web_application.getWarStream();
            if (stream == null) {
                throw new TomcatException("Cannot install WebApplication " + web_application.getName()
                        + ". The referenced war " + "file does not exist.");
            }
            JarInputStream jis = new JarInputStream(stream);
            File destDir = new File(tomcatpath, "webapps/" + folder);

            byte[] buffer = new byte[4096];
            JarEntry file;
            while ((file = jis.getNextJarEntry()) != null) {
                File f = new File(destDir + java.io.File.separator + file.getName());
                if (file.isDirectory()) { // if its a directory, create it
                    f.mkdirs();
                    continue;
                }
                if (!f.getParentFile().exists()) {
                    f.getParentFile().mkdirs();
                }

                java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
                int read;
                while ((read = jis.read(buffer)) != -1) {
                    fos.write(buffer, 0, read);
                }
                fos.flush();
                fos.close();
            }
            jis.close();
        }
        web_application.configure(new File(tomcatpath, "webapps/" + folder).getPath());

        StandardEngine engine = (StandardEngine) cat.getServer().findServices()[0].getContainer();
        Container container = engine.findChild(engine.getDefaultHost());

        StandardContext ctx = new StandardContext();
        String url = (web_application.getName() == "" ? "" : "/") + web_application.getName();
        ctx.setName(url);
        ctx.setPath(url);
        ctx.setDocBase(new File(tomcatpath, "webapps/" + folder).getPath());

        ctx.addLifecycleListener(new DefaultWebXmlListener());
        ctx.setConfigFile(getWebappConfigFile(new File(tomcatpath, "webapps/" + folder).getPath(), url));

        ContextConfig ctxCfg = new ContextConfig();
        ctx.addLifecycleListener(ctxCfg);

        ctxCfg.setDefaultWebXml("fr/gael/dhus/server/http/global-web.xml");

        container.addChild(ctx);

        contexts.add(ctx);

        List<WebServlet> servlets = web_application.getServlets();

        for (WebServlet servlet : servlets) {
            addServlet(ctx, servlet.getServletName(), servlet.getUrlPattern(), servlet.getServlet(),
                    servlet.isLoadOnStartup());
        }

        List<String> welcomeFiles = web_application.getWelcomeFiles();

        for (String welcomeFile : welcomeFiles) {
            ctx.addWelcomeFile(welcomeFile);
        }

        if (web_application.getAllow() != null || web_application.getDeny() != null) {
            RemoteIpValve valve = new RemoteIpValve();
            valve.setRemoteIpHeader("x-forwarded-for");
            valve.setProxiesHeader("x-forwarded-by");
            valve.setProtocolHeader("x-forwarded-proto");
            ctx.addValve(valve);

            RemoteAddrValve valve_addr = new RemoteAddrValve();
            valve_addr.setAllow(web_application.getAllow());
            valve_addr.setDeny(web_application.getDeny());
            ctx.addValve(valve_addr);
        }
    } catch (Exception e) {
        throw new TomcatException("Cannot install service", e);
    }
}

From source file:fr.gael.dhus.server.http.TomcatServer.java

public void install(fr.gael.dhus.server.http.WebApplication web_application) throws TomcatException {
    logger.info("Installing webapp " + web_application);
    String appName = web_application.getName();
    String folder;// w  ww. j a  v  a 2s .c  om

    if (appName.trim().isEmpty()) {
        folder = "ROOT";
    } else {
        folder = appName;
    }

    try {
        if (web_application.hasWarStream()) {
            InputStream stream = web_application.getWarStream();
            if (stream == null) {
                throw new TomcatException("Cannot install webApplication " + web_application.getName()
                        + ". The referenced war file does not exist.");
            }
            JarInputStream jis = new JarInputStream(stream);
            File destDir = new File(tomcatpath, "webapps/" + folder);

            byte[] buffer = new byte[4096];
            JarEntry file;
            while ((file = jis.getNextJarEntry()) != null) {
                File f = new File(destDir + java.io.File.separator + file.getName());
                if (file.isDirectory()) { // if its a directory, create it
                    f.mkdirs();
                    continue;
                }
                if (!f.getParentFile().exists()) {
                    f.getParentFile().mkdirs();
                }

                java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
                int read;
                while ((read = jis.read(buffer)) != -1) {
                    fos.write(buffer, 0, read);
                }
                fos.flush();
                fos.close();
            }
            jis.close();
        }
        web_application.configure(new File(tomcatpath, "webapps/" + folder).getPath());

        StandardEngine engine = (StandardEngine) cat.getServer().findServices()[0].getContainer();
        Container container = engine.findChild(engine.getDefaultHost());

        StandardContext ctx = new StandardContext();
        String url = (web_application.getName() == "" ? "" : "/") + web_application.getName();
        ctx.setName(url);
        ctx.setPath(url);
        ctx.setDocBase(new File(tomcatpath, "webapps/" + folder).getPath());

        ctx.addLifecycleListener(new DefaultWebXmlListener());
        ctx.setConfigFile(getWebappConfigFile(new File(tomcatpath, "webapps/" + folder).getPath(), url));

        ContextConfig ctxCfg = new ContextConfig();
        ctx.addLifecycleListener(ctxCfg);

        ctxCfg.setDefaultWebXml("fr/gael/dhus/server/http/global-web.xml");

        container.addChild(ctx);

        List<String> welcomeFiles = web_application.getWelcomeFiles();

        for (String welcomeFile : welcomeFiles) {
            ctx.addWelcomeFile(welcomeFile);
        }

        if (web_application.getAllow() != null || web_application.getDeny() != null) {
            RemoteIpValve valve = new RemoteIpValve();
            valve.setRemoteIpHeader("x-forwarded-for");
            valve.setProxiesHeader("x-forwarded-by");
            valve.setProtocolHeader("x-forwarded-proto");
            ctx.addValve(valve);

            RemoteAddrValve valve_addr = new RemoteAddrValve();
            valve_addr.setAllow(web_application.getAllow());
            valve_addr.setDeny(web_application.getDeny());
            ctx.addValve(valve_addr);
        }

        web_application.checkInstallation();
    } catch (Exception e) {
        throw new TomcatException("Cannot install webApplication " + web_application.getName(), e);
    }
}

From source file:com.datatorrent.stram.client.StramAppLauncher.java

private void init(String tmpName) throws Exception {
    File baseDir = StramClientUtils.getUserDTDirectory();
    baseDir = new File(new File(baseDir, "appcache"), tmpName);
    baseDir.mkdirs();/* w  w  w  . j ava 2 s.  co m*/
    LinkedHashSet<URL> clUrls;
    List<String> classFileNames = new ArrayList<String>();

    if (jarFile != null) {
        JarFileContext jfc = new JarFileContext(new java.util.jar.JarFile(jarFile), mvnBuildClasspathOutput);
        jfc.cacheDir = baseDir;

        java.util.Enumeration<JarEntry> entriesEnum = jfc.jarFile.entries();
        while (entriesEnum.hasMoreElements()) {
            java.util.jar.JarEntry jarEntry = entriesEnum.nextElement();
            if (!jarEntry.isDirectory()) {
                if (jarEntry.getName().endsWith("pom.xml")) {
                    jfc.pomEntry = jarEntry;
                } else if (jarEntry.getName().endsWith(".app.properties")) {
                    File targetFile = new File(baseDir, jarEntry.getName());
                    FileUtils.copyInputStreamToFile(jfc.jarFile.getInputStream(jarEntry), targetFile);
                    appResourceList.add(new PropertyFileAppFactory(targetFile));
                } else if (jarEntry.getName().endsWith(".class")) {
                    classFileNames.add(jarEntry.getName());
                }
            }
        }

        URL mainJarUrl = new URL("jar", "", "file:" + jarFile.getAbsolutePath() + "!/");
        jfc.urls.add(mainJarUrl);

        deployJars = Sets.newLinkedHashSet();
        // add all jar files from same directory
        Collection<File> jarFiles = FileUtils.listFiles(jarFile.getParentFile(), new String[] { "jar" }, false);
        for (File lJarFile : jarFiles) {
            jfc.urls.add(lJarFile.toURI().toURL());
            deployJars.add(lJarFile);
        }

        // resolve dependencies
        List<Resolver> resolvers = Lists.newArrayList();

        String resolverConfig = this.propertiesBuilder.conf.get(CLASSPATH_RESOLVERS_KEY_NAME, null);
        if (!StringUtils.isEmpty(resolverConfig)) {
            resolvers = new ClassPathResolvers().createResolvers(resolverConfig);
        } else {
            // default setup if nothing was configured
            String manifestCp = jfc.jarFile.getManifest().getMainAttributes()
                    .getValue(ManifestResolver.ATTR_NAME);
            if (manifestCp != null) {
                File repoRoot = new File(System.getProperty("user.home") + "/.m2/repository");
                if (repoRoot.exists()) {
                    LOG.debug("Resolving manifest attribute {} based on {}", ManifestResolver.ATTR_NAME,
                            repoRoot);
                    resolvers.add(new ClassPathResolvers.ManifestResolver(repoRoot));
                } else {
                    LOG.warn("Ignoring manifest attribute {} because {} does not exist.",
                            ManifestResolver.ATTR_NAME, repoRoot);
                }
            }
        }

        for (Resolver r : resolvers) {
            r.resolve(jfc);
        }

        jfc.jarFile.close();

        URLConnection urlConnection = mainJarUrl.openConnection();
        if (urlConnection instanceof JarURLConnection) {
            // JDK6 keeps jar file shared and open as long as the process is running.
            // we want the jar file to be opened on every launch to pick up latest changes
            // http://abondar-howto.blogspot.com/2010/06/howto-unload-jar-files-loaded-by.html
            // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4167874
            ((JarURLConnection) urlConnection).getJarFile().close();
        }
        clUrls = jfc.urls;
    } else {
        clUrls = new LinkedHashSet<URL>();
    }

    // add the jar dependencies
    /*
        if (cp == null) {
          // dependencies from parent loader, if classpath can't be found from pom
          ClassLoader baseCl = StramAppLauncher.class.getClassLoader();
          if (baseCl instanceof URLClassLoader) {
            URL[] baseUrls = ((URLClassLoader)baseCl).getURLs();
            // launch class path takes precedence - add first
            clUrls.addAll(Arrays.asList(baseUrls));
          }
        }
    */

    String libjars = propertiesBuilder.conf.get(LIBJARS_CONF_KEY_NAME);
    if (libjars != null) {
        processLibJars(libjars, clUrls);
    }

    for (URL baseURL : clUrls) {
        LOG.debug("Dependency: {}", baseURL);
    }

    this.launchDependencies = clUrls;

    // we have the classpath dependencies, scan for java configurations
    findAppConfigClasses(classFileNames);

}