Example usage for java.util.jar JarEntry JarEntry

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

Introduction

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

Prototype

public JarEntry(JarEntry je) 

Source Link

Document

Creates a new JarEntry with fields taken from the specified JarEntry object.

Usage

From source file:gov.redhawk.rap.internal.PluginProviderServlet.java

private void addFiles(final JarOutputStream out, final IPath path, final File... listFiles) throws IOException {
    for (final File f : listFiles) {
        if (f.getName().charAt(0) == '.') {
            continue;
        } else if (f.getName().equals("MANIFEST.MF")) {
            continue;
        }/*from   w  w w.  j a v  a2s .  com*/
        final IPath filePath = path.append(f.getName());
        String str = filePath.toString();
        if (str.startsWith("/")) {
            str = str.substring(1);
        }
        if (f.isDirectory()) {
            if (!str.endsWith("/")) {
                str = str + "/";
            }
            final JarEntry entry = new JarEntry(str);
            entry.setSize(0);
            entry.setTime(f.lastModified());
            out.putNextEntry(entry);
            out.closeEntry();
            addFiles(out, filePath, f.listFiles());
        } else {
            final JarEntry entry = new JarEntry(str);
            entry.setSize(f.length());
            entry.setTime(f.lastModified());
            out.putNextEntry(entry);
            final FileInputStream istream = new FileInputStream(f);
            try {
                IOUtils.copy(istream, out);
            } finally {
                istream.close();
            }
            out.closeEntry();
        }
    }
}

From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File hudsonTemplateWar = new File(warTemplateFile);

    if (!hudsonTemplateWar.exists() || !hudsonTemplateWar.isFile()) {
        String message = "The given Hudson template WAR [" + hudsonTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);/* ww  w .ja v a 2 s .  c om*/
        throw new IllegalStateException(message);
    }

    String deployLocation = hudsonWarNamingStrategy.getWarFilePath(configuration);

    File hudsonDeployFile = new File(deployLocation);

    if (hudsonDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + hudsonDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile hudsonTemplateWarJar = new JarFile(hudsonTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = hudsonTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(hudsonTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct HUDSON_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedHudsonWar = File.createTempFile("hudson", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedHudsonWar),
                hudsonTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = hudsonTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(hudsonTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into it's deployment location so that it can be picked up and deployed by Tomcat.
        FileUtils.moveFile(updatedHudsonWar, hudsonDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:JarBuilder.java

/** Adds the file to the given path and name
 *
 * @param file     the file to be added/*from w w  w .j a  va  2 s.  c o  m*/
 * @param parent   the directory to the path in which the file is to be added
 * @param fileName the name of the file in the archive
 */
public void addFile(File file, String parent, String fileName) throws IOException {
    byte data[] = new byte[2048];

    FileInputStream fi = new FileInputStream(file.getAbsolutePath());
    BufferedInputStream origin = new BufferedInputStream(fi, 2048);

    JarEntry entry = new JarEntry(makeName(parent, fileName));
    _output.putNextEntry(entry);

    int count = origin.read(data, 0, 2048);
    while (count != -1) {
        _output.write(data, 0, count);
        count = origin.read(data, 0, 2048);
    }

    origin.close();
}

From source file:com.ikanow.aleph2.analytics.spark.services.SparkCompilerService.java

/** Compiles a scala class
 * @param script/*ww w . j  av a 2s .  c om*/
 * @param clazz_name
 * @return
 * @throws IOException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ClassNotFoundException
 */
public Tuple2<ClassLoader, Object> buildClass(final String script, final String clazz_name,
        final Optional<IBucketLogger> logger)
        throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    final String relative_dir = "./script_classpath/";
    new File(relative_dir).mkdirs();

    final File source_file = new File(relative_dir + clazz_name + ".scala");
    FileUtils.writeStringToFile(source_file, script);

    final String this_path = LiveInjector.findPathJar(this.getClass(), "./dummy.jar");
    final File f = new File(this_path);
    final File fp = new File(f.getParent());
    final String classpath = Arrays.stream(fp.listFiles()).map(ff -> ff.toString())
            .filter(ff -> ff.endsWith(".jar")).collect(Collectors.joining(":"));

    // Need this to make the URL classloader be used, not the system classloader (which doesn't know about Aleph2..)

    final Settings s = new Settings();
    s.classpath().value_$eq(System.getProperty("java.class.path") + classpath);
    s.usejavacp().scala$tools$nsc$settings$AbsSettings$AbsSetting$$internalSetting_$eq(true);
    final StoreReporter reporter = new StoreReporter();
    final Global g = new Global(s, reporter);
    final Run r = g.new Run();
    r.compile(JavaConverters.asScalaBufferConverter(Arrays.<String>asList(source_file.toString())).asScala()
            .toList());

    if (reporter.hasErrors() || reporter.hasWarnings()) {
        final String errors = "Compiler: Errors/warnings (**to get to user script line substract 22**): "
                + JavaConverters.asJavaSetConverter(reporter.infos()).asJava().stream()
                        .map(info -> info.toString()).collect(Collectors.joining(" ;; "));
        logger.ifPresent(l -> l.log(reporter.hasErrors() ? Level.ERROR : Level.DEBUG, false, () -> errors,
                () -> "SparkScalaInterpreterTopology", () -> "compile"));

        //ERROR:
        if (reporter.hasErrors()) {
            System.err.println(errors);
        }
    }
    // Move any class files (eg including sub-classes)
    Arrays.stream(fp.listFiles()).filter(ff -> ff.toString().endsWith(".class"))
            .forEach(Lambdas.wrap_consumer_u(ff -> {
                FileUtils.moveFile(ff, new File(relative_dir + ff.getName()));
            }));

    // Create a JAR file...

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    final JarOutputStream target = new JarOutputStream(new FileOutputStream("./script_classpath.jar"),
            manifest);
    Arrays.stream(new File(relative_dir).listFiles()).forEach(Lambdas.wrap_consumer_i(ff -> {
        JarEntry entry = new JarEntry(ff.getName());
        target.putNextEntry(entry);
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(ff))) {
            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        }
    }));
    target.close();

    final String created = "Created = " + new File("./script_classpath.jar").toURI().toURL() + " ... "
            + Arrays.stream(new File(relative_dir).listFiles()).map(ff -> ff.toString())
                    .collect(Collectors.joining(";"));
    logger.ifPresent(l -> l.log(Level.DEBUG, true, () -> created, () -> "SparkScalaInterpreterTopology",
            () -> "compile"));

    final Tuple2<ClassLoader, Object> o = Lambdas.get(Lambdas.wrap_u(() -> {
        _cl.set(new java.net.URLClassLoader(
                Arrays.asList(new File("./script_classpath.jar").toURI().toURL()).toArray(new URL[0]),
                Thread.currentThread().getContextClassLoader()));
        Object o_ = _cl.get().loadClass("ScriptRunner").newInstance();
        return Tuples._2T(_cl.get(), o_);
    }));
    return o;
}

From source file:gov.nih.nci.restgen.util.JarHelper.java

/**
 * Recursively jars up the given path under the given directory.
 */// w w  w  . j  a  v a 2 s.c  o  m
private void jarDir(File dirOrFile2jar, JarOutputStream jos, String path) throws IOException {
    //if (mVerbose)
    {
        //System.out.println("checking " + dirOrFile2jar);
    }
    if (dirOrFile2jar.isDirectory()) {
        String[] dirList = dirOrFile2jar.list();
        String subPath = (path == null) ? "" : (path + dirOrFile2jar.getName() + SEP);
        if (path != null) {
            JarEntry je = new JarEntry(subPath);
            je.setTime(dirOrFile2jar.lastModified());
            jos.putNextEntry(je);
            jos.flush();
            jos.closeEntry();
        }
        for (int i = 0; i < dirList.length; i++) {
            File f = new File(dirOrFile2jar, dirList[i]);
            jarDir(f, jos, subPath);
        }
    } else {
        if (dirOrFile2jar.getCanonicalPath().equals(mDestJarName)) {
            //if (mVerbose)
            {
                //System.out.println("skipping " + dirOrFile2jar.getPath());
            }
            return;
        }

        if (mVerbose) {
            //System.out.println("adding " + dirOrFile2jar.getPath());
        }
        FileInputStream fis = new FileInputStream(dirOrFile2jar);
        try {
            JarEntry entry = new JarEntry(path + dirOrFile2jar.getName());
            entry.setTime(dirOrFile2jar.lastModified());
            jos.putNextEntry(entry);
            while ((mByteCount = fis.read(mBuffer)) != -1) {
                jos.write(mBuffer, 0, mByteCount);
                if (mVerbose) {
                    //System.out.println("wrote " + mByteCount + " bytes");
                }
            }
            jos.flush();
            jos.closeEntry();
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            fis.close();
        }
    }
}

From source file:com.threerings.cast.bundle.tools.MetadataBundlerTask.java

/**
 * Advances to the next named entry in the bundle and returns the stream to which to write
 *  that entry.//from   ww  w . j  a  va  2  s.c  o  m
 */
protected OutputStream nextEntry(OutputStream lastEntry, String path) throws IOException {
    ((JarOutputStream) lastEntry).putNextEntry(new JarEntry(path));
    return lastEntry;
}

From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File jenkinsTemplateWar = new File(warTemplateFile);

    if (!jenkinsTemplateWar.exists() || !jenkinsTemplateWar.isFile()) {
        String message = "The given Jenkins template WAR [" + jenkinsTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);//from w w w  .j  a  v a 2s. com
        throw new IllegalStateException(message);
    }

    String pathProperty = perOrg ? configuration.getOrganizationIdentifier()
            : configuration.getProjectIdentifier();

    String deployedUrl = configuration.getProperties().get(ProjectServiceConfiguration.PROFILE_BASE_URL)
            + jenkinsPath + pathProperty + "/jenkins/";
    deployedUrl.replace("//", "/");
    URL deployedJenkinsUrl;
    try {
        deployedJenkinsUrl = new URL(deployedUrl);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    String webappName = deployedJenkinsUrl.getPath();
    if (webappName.startsWith("/")) {
        webappName = webappName.substring(1);
    }
    if (webappName.endsWith("/")) {
        webappName = webappName.substring(0, webappName.length() - 1);
    }
    webappName = webappName.replace("/", "#");
    webappName = webappName + ".war";

    // Calculate our final filename.

    String deployLocation = targetWebappsDir + webappName;

    File jenkinsDeployFile = new File(deployLocation);

    if (jenkinsDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + jenkinsDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile jenkinsTemplateWarJar = new JarFile(jenkinsTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = jenkinsTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(jenkinsTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct JENKINS_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedJenkinsWar = File.createTempFile("jenkins", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedJenkinsWar),
                jenkinsTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = jenkinsTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(jenkinsTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into its deployment location so that it can be picked up and deployed by the app server.
        FileUtils.moveFile(updatedJenkinsWar, jenkinsDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:com.moss.nomad.core.packager.Packager.java

public void write(OutputStream o) throws Exception {

    JarOutputStream out = new JarOutputStream(o);

    {//from  ww w  .  j a  va  2 s  .  c  om
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(container, bao);

        byte[] containerIndex = bao.toByteArray();

        JarEntry entry = new JarEntry("META-INF/container.xml");
        out.putNextEntry(entry);
        out.write(containerIndex);
    }

    final byte[] buffer = new byte[1024 * 10]; //10k buffer

    for (String path : dependencies.keySet()) {
        ResolvedDependencyInfo info = dependencies.get(path);

        JarEntry entry = new JarEntry(path);
        out.putNextEntry(entry);

        InputStream in = new FileInputStream(info.file());
        for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
            out.write(buffer, 0, numRead);
        }
        in.close();
    }

    out.close();
}

From source file:ai.h2o.servicebuilder.Util.java

/**
 * Create jar archive out of files list. Names in archive have paths starting from relativeToDir
 *
 * @param tobeJared     list of files//from  w w  w . ja va  2 s  .c  o m
 * @param relativeToDir starting directory for paths
 * @return jar as byte array
 * @throws IOException
 */
public static byte[] createJarArchiveByteArray(File[] tobeJared, String relativeToDir) throws IOException {
    int BUFFER_SIZE = 10240;
    byte buffer[] = new byte[BUFFER_SIZE];
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    JarOutputStream out = new JarOutputStream(stream, new Manifest());

    for (File t : tobeJared) {
        if (t == null || !t.exists() || t.isDirectory()) {
            if (t != null && !t.isDirectory())
                logger.error("Can't add to jar {}", t);
            continue;
        }
        // Create jar entry
        String filename = t.getPath().replace(relativeToDir, "").replace("\\", "/");
        //      if (filename.endsWith("MANIFEST.MF")) { // skip to avoid duplicates
        //        continue;
        //      }
        JarEntry jarAdd = new JarEntry(filename);
        jarAdd.setTime(t.lastModified());
        out.putNextEntry(jarAdd);

        // Write file to archive
        FileInputStream in = new FileInputStream(t);
        while (true) {
            int nRead = in.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            out.write(buffer, 0, nRead);
        }
        in.close();
    }

    out.close();
    stream.close();
    return stream.toByteArray();
}

From source file:com.jhash.oimadmin.Utils.java

public static void createJarFileFromDirectory(String directory, String jarFileName) {
    File jarDirectory = new File(directory);
    try (JarOutputStream jarFileOutputStream = new JarOutputStream(new FileOutputStream(jarFileName))) {
        for (Iterator<File> fileIterator = FileUtils.iterateFiles(jarDirectory, null, true); fileIterator
                .hasNext();) {//from   w  w  w .j a v  a2s.  com
            File inputFile = fileIterator.next();
            String inputFileName = inputFile.getAbsolutePath();
            String directoryFileName = jarDirectory.getAbsolutePath();
            String relativeInputFileName = inputFileName.substring(directoryFileName.length() + 1);
            JarEntry newFileEntry = new JarEntry(relativeInputFileName);
            newFileEntry.setTime(System.currentTimeMillis());
            jarFileOutputStream.putNextEntry(newFileEntry);
            jarFileOutputStream.write(FileUtils.readFileToByteArray(inputFile));
        }
    } catch (Exception exception) {
        throw new OIMAdminException(
                "Failed to create the jar file " + jarFileName + " from directory " + directory, exception);
    }
}