Example usage for java.util.jar JarFile JarFile

List of usage examples for java.util.jar JarFile JarFile

Introduction

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

Prototype

public JarFile(File file) throws IOException 

Source Link

Document

Creates a new JarFile to read from the specified File object.

Usage

From source file:edu.stanford.muse.email.JarDocCache.java

public void exportAsMbox(String outFilename, String prefix, Collection<EmailDocument> selectedDocs,
        boolean append) throws IOException, GeneralSecurityException, ClassNotFoundException {
    PrintWriter mbox = new PrintWriter(new FileOutputStream("filename", append));
    Map<Integer, Document> allHeadersMap = getAllHeaders(prefix);
    Map<Integer, Document> selectedHeadersMap = new LinkedHashMap<Integer, Document>();
    Set<EmailDocument> selectedDocsSet = new LinkedHashSet<EmailDocument>(selectedDocs);

    for (Integer I : allHeadersMap.keySet()) {
        EmailDocument ed = (EmailDocument) allHeadersMap.get(I);
        if (selectedDocsSet.contains(ed))
            selectedHeadersMap.put(I, ed);
    }//from w  w  w. ja v a2 s. co m

    JarFile contentJar = null;
    try {
        contentJar = new JarFile(baseDir + File.separator + prefix + ".contents");
    } catch (Exception e) {
        Util.print_exception(e, log);
        return;
    }

    Enumeration<JarEntry> contentEntries = contentJar.entries();
    String suffix = ".content";
    while (contentEntries.hasMoreElements()) {
        JarEntry c_je = contentEntries.nextElement();
        String s = c_je.getName();
        if (!s.endsWith(suffix))
            continue;
        int index = -1;
        String idx_str = s.substring(0, s.length() - suffix.length());
        try {
            index = Integer.parseInt(idx_str);
        } catch (Exception e) {
            log.error("Funny file in header: " + index);
        }

        EmailDocument ed = (EmailDocument) selectedHeadersMap.get(index);
        if (ed == null)
            continue; // not selected

        byte[] b = Util.getBytesFromStream(contentJar.getInputStream(c_je));
        String contents = new String(b, "UTF-8");
        EmailUtils.printHeaderToMbox(ed, mbox);
        EmailUtils.printBodyAndAttachmentsToMbox(contents, ed, mbox, null);
        mbox.println(contents);
    }
}

From source file:ca.weblite.jdeploy.JDeploy.java

private String[] findClassPath(File jarFile) throws IOException {
    Manifest m = new JarFile(jarFile).getManifest();
    //System.out.println(m.getEntries());
    String cp = m.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
    //System.out.println("Class path is "+cp);
    if (cp != null) {
        return cp.split(" ");
    } else {/*from w  w  w.  j av a  2s .  c  o m*/
        return new String[0];
    }
}

From source file:com.taobao.android.builder.tools.multidex.mutli.JarRefactor.java

private Collection<File> generateFirstDexJar(List<String> mainDexList, Collection<File> files)
        throws IOException {

    List<File> jarList = new ArrayList<>();
    List<File> folderList = new ArrayList<>();
    for (File file : files) {
        if (file.isDirectory()) {
            folderList.add(file);/*  ww  w.  j a va  2 s.  c  o  m*/
        } else {
            jarList.add(file);
        }
    }

    File dir = new File(appVariantContext.getScope().getGlobalScope().getIntermediatesDir(),
            "fastmultidex/" + appVariantContext.getVariantName());
    FileUtils.deleteDirectory(dir);
    dir.mkdirs();

    if (!folderList.isEmpty()) {
        File mergedJar = new File(dir, "jarmerging/combined.jar");
        mergedJar.getParentFile().mkdirs();
        mergedJar.delete();
        mergedJar.createNewFile();
        JarMerger jarMerger = new JarMerger(mergedJar.toPath());
        for (File folder : folderList) {
            jarMerger.addDirectory(folder.toPath());
        }
        jarMerger.close();
        if (mergedJar.length() > 0) {
            jarList.add(mergedJar);
        }
    }

    List<File> result = new ArrayList<>();
    File maindexJar = new File(dir, DexMerger.FASTMAINDEX_JAR + ".jar");

    JarOutputStream mainJarOuputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(maindexJar)));

    //First order
    Collections.sort(jarList, new NameComparator());

    for (File jar : jarList) {
        File outJar = new File(dir, FileNameUtils.getUniqueJarName(jar) + ".jar");

        result.add(outJar);
        JarFile jarFile = new JarFile(jar);
        JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));
        Enumeration<JarEntry> jarFileEntries = jarFile.entries();

        List<String> pathList = new ArrayList<>();
        while (jarFileEntries.hasMoreElements()) {
            JarEntry ze = jarFileEntries.nextElement();
            String pathName = ze.getName();
            if (mainDexList.contains(pathName)) {
                copyStream(jarFile.getInputStream(ze), mainJarOuputStream, ze, pathName);
                pathList.add(pathName);
            }
        }

        if (!pathList.isEmpty()) {
            jarFileEntries = jarFile.entries();
            while (jarFileEntries.hasMoreElements()) {
                JarEntry ze = jarFileEntries.nextElement();
                String pathName = ze.getName();
                if (!pathList.contains(pathName)) {
                    copyStream(jarFile.getInputStream(ze), jos, ze, pathName);
                }
            }
        }

        jarFile.close();
        IOUtils.closeQuietly(jos);

        if (pathList.isEmpty()) {
            FileUtils.copyFile(jar, outJar);
        }
        if (!appVariantContext.getAtlasExtension().getTBuildConfig().isFastProguard() && files.size() == 1) {
            JarUtils.splitMainJar(result, outJar, 1, MAX_CLASSES);
        }
    }

    IOUtils.closeQuietly(mainJarOuputStream);

    Collections.sort(result, new NameComparator());

    result.add(0, maindexJar);

    return result;
}

From source file:org.apache.openejb.config.DeploymentLoader.java

private static void addConnectorModules(final AppModule appModule, final WebModule webModule)
        throws OpenEJBException {
    // WEB-INF//from w  ww.  ja v a  2  s.  c  o  m
    if (webModule.getAltDDs().containsKey("ra.xml")) {
        final String jarLocation = new File(webModule.getJarLocation(), "/WEB-INF/classes").getAbsolutePath();
        final ConnectorModule connectorModule = createConnectorModule(jarLocation, jarLocation,
                webModule.getClassLoader(), webModule.getModuleId() + "RA",
                (URL) webModule.getAltDDs().get("ra.xml"));
        appModule.getConnectorModules().add(connectorModule);
    }

    // .rar
    for (final URL url : webModule.getRarUrls()) {
        try {
            final File file = URLs.toFile(url);
            if (file.getName().endsWith(".rar")) {
                final String jarLocation = file.getAbsolutePath();
                final ConnectorModule connectorModule = createConnectorModule(jarLocation, jarLocation,
                        webModule.getClassLoader(), null);
                appModule.getConnectorModules().add(connectorModule);
            }
        } catch (final Exception e) {
            logger.error("error processing url " + url.toExternalForm(), e);
        }
    }

    for (final URL url : webModule.getScannableUrls()) {
        try {
            final File file = URLs.toFile(url);
            if (file.getName().endsWith(".jar")) {
                final JarFile jarFile = new JarFile(file);

                // TODO: better management of altdd
                String name = (ALTDD != null ? ALTDD + "." : "") + "ra.xml";

                JarEntry entry = jarFile.getJarEntry(name);
                if (entry == null) {
                    name = "META-INF/" + name;
                    entry = jarFile.getJarEntry(name);
                }
                if (entry == null) {
                    continue;
                }

                final String jarLocation = file.getAbsolutePath();
                final ConnectorModule connectorModule = createConnectorModule(jarLocation, jarLocation,
                        webModule.getClassLoader(), null);
                appModule.getConnectorModules().add(connectorModule);
            }
        } catch (final Exception e) {
            logger.error("error processing url " + url.toExternalForm(), e);
        }
    }
}

From source file:com.taobao.android.apatch.MergePatch.java

private void fillManifest(Attributes main) throws IOException {
    JarFile jarFile;//from w  ww  .  jav  a2 s.c  om
    Manifest manifest;
    StringBuffer fromBuffer = new StringBuffer();
    StringBuffer toBuffer = new StringBuffer();
    String from;
    String to;
    String name;
    // String classes;
    for (File file : patchs) {
        jarFile = new JarFile(file);
        JarEntry dexEntry = jarFile.getJarEntry("META-INF/PATCH.MF");
        manifest = new Manifest(jarFile.getInputStream(dexEntry));
        Attributes attributes = manifest.getMainAttributes();

        from = attributes.getValue("From-File");
        if (fromBuffer.length() > 0) {
            fromBuffer.append(',');
        }
        fromBuffer.append(from);
        to = attributes.getValue("To-File");
        if (toBuffer.length() > 0) {
            toBuffer.append(',');
        }
        toBuffer.append(to);

        name = attributes.getValue("Patch-Name");
        // classes = attributes.getValue(name + "-Patch-Classes");
        main.putValue(name + "-Patch-Classes", attributes.getValue(name + "-Patch-Classes"));
        main.putValue(name + "-Prepare-Classes", attributes.getValue(name + "-Prepare-Classes"));
        main.putValue(name + "-Used-Methods", attributes.getValue(name + "-Used-Methods"));
        main.putValue(name + "-Modified-Classes", attributes.getValue(name + "-Modified-Classes"));
        main.putValue(name + "-Used-Classes", attributes.getValue(name + "-Used-Classes"));
        main.putValue(name + "-add-classes", attributes.getValue(name + "-add-classes"));

    }
    main.putValue("From-File", fromBuffer.toString());
    main.putValue("To-File", toBuffer.toString());
}

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 ww w  . ja v a 2 s.com*/
    }
    //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 ava 2  s  .com
    }
    //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.tajo.catalog.store.XMLCatalogSchemaManager.java

protected String[] listJarResources(URL dirURL, FilenameFilter filter) throws IOException, URISyntaxException {
    String[] files = new String[0];
    String spec = dirURL.getFile();
    int seperator = spec.indexOf("!/");

    if (seperator == -1) {
        return files;
    }//  w  w w . j  ava2s . co m

    URL jarFileURL = new URL(spec.substring(0, seperator));
    Set<String> filesSet = new HashSet<>();

    try (JarFile jarFile = new JarFile(jarFileURL.toURI().getPath())) {
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();

            if (entry.isDirectory()) {
                continue;
            }

            String entryName = entry.getName();

            if (entryName.indexOf(schemaPath) > -1 && filter.accept(null, entryName)) {
                filesSet.add(entryName);
            }
        }
    }

    if (!filesSet.isEmpty()) {
        files = new String[filesSet.size()];
        files = filesSet.toArray(files);
    }

    return files;
}

From source file:com.ms.commons.test.classloader.IntlTestURLClassPath.java

private static URL translateURL(URL url) throws Exception {
    URLClassLoader ucl = new URLClassLoader(new URL[] { url });

    // URL?autoconfig
    List<URL> autoConfigXmlList = AutoConfigUtil.loadAllAutoConfigFilesWithFind(ucl);
    if ((autoConfigXmlList == null) || (autoConfigXmlList.size() == 0)) {
        return url;
    }/*w ww .  jav  a 2 s. co m*/

    AutoConfigMap acm = AutoConfigUtil.loadAutoConfigMapWithFind(ucl, IntlTestProperties.PROPERTIES);
    // ??URL
    boolean urlTranslated = false;
    // 
    String outputPath;
    if ("file".equals(url.getProtocol()) && !url.toString().toLowerCase().endsWith(".jar")) {
        outputPath = FileUtil.convertURLToFilePath(url);
    } else if (url.toString().toLowerCase().endsWith(".jar")) {
        String fileN = FileUtil.convertURLToFile(url).getName();
        String jarUrlPath = fileN + "@" + url.toString().hashCode();
        jarUrlPath = jarUrlPath.replace(".jar", "").replace("alibaba", "");
        outputPath = TESTCASE_JAR_TEMP_DIR + File.separator + StringUtil.replaceNoWordChars(jarUrlPath);
        // ??????
        File signature = new File(outputPath + File.separator + TESTCASE_JAR_SIGNATURE);

        StringBuilder refAst = new StringBuilder();
        if (isOutOfDate(signature, url, refAst)) {
            // JAR??JAR?JAR??
            FileUtil.clearAndMakeDirs(outputPath);

            expandJarTo(new JarFile(FileUtil.convertURLToFile(url)), outputPath);

            FileUtils.writeStringToFile(signature, refAst.toString());
        }

        urlTranslated = true;
    } else {
        throw new RuntimeException("URL protocol unknow:" + url);
    }

    // ?autoconfig?
    System.err.println("Auto config for:" + url);
    for (AutoConfigItem antxConfigResourceItem : acm.values()) {
        AutoConfigUtil.autoConfigFile(ucl, IntlTestProperties.PROPERTIES, antxConfigResourceItem, outputPath,
                true);
    }

    return urlTranslated ? (new File(outputPath)).toURI().toURL() : url;
}

From source file:ca.weblite.jdeploy.JDeploy.java

private File[] findJarCandidates() throws IOException {
    File[] jars = findCandidates(directory.toPath().getFileSystem().getPathMatcher("glob:**/*.jar"));
    List<File> out = new ArrayList<File>();
    // We only want executable jars
    for (File f : jars) {
        Manifest m = new JarFile(f).getManifest();
        //System.out.println(m.getEntries());
        if (m != null) {
            Attributes atts = m.getMainAttributes();
            if (atts.containsKey(Attributes.Name.MAIN_CLASS)) {
                //executable jar
                out.add(f);/*from w ww.ja v a 2 s  . c om*/
            }
        }
    }
    return out.toArray(new File[out.size()]);
}