Example usage for java.util.jar JarEntry getSize

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

Introduction

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

Prototype

public long getSize() 

Source Link

Document

Returns the uncompressed size of the entry data.

Usage

From source file:com.android.build.gradle.integration.application.ExternalBuildPluginTest.java

@Test
public void testBuild() throws ProcessException, IOException, ParserConfigurationException, SAXException {
    FileUtils.write(mProject.getBuildFile(),
            "" + "apply from: \"../commonHeader.gradle\"\n" + "buildscript {\n "
                    + "  apply from: \"../commonBuildScript.gradle\"\n" + "}\n" + "\n"
                    + "apply plugin: 'base'\n" + "apply plugin: 'com.android.external.build'\n" + "\n"
                    + "externalBuild {\n" + "  executionRoot = $/" + mProject.getTestDir().getAbsolutePath()
                    + "/$\n" + "  buildManifestPath = $/" + manifestFile.getAbsolutePath() + "/$\n" + "}\n");

    mProject.executor().withInstantRun(23, ColdswapMode.AUTO).withPackaging(mPackaging).run("clean", "process");

    InstantRunBuildContext instantRunBuildContext = loadFromBuildInfo();
    assertThat(instantRunBuildContext.getPreviousBuilds()).hasSize(1);
    assertThat(instantRunBuildContext.getLastBuild()).isNotNull();
    assertThat(instantRunBuildContext.getLastBuild().getArtifacts()).hasSize(1);
    InstantRunBuildContext.Build fullBuild = instantRunBuildContext.getLastBuild();
    assertThat(fullBuild.getVerifierStatus().get()).isEqualTo(InstantRunVerifierStatus.INITIAL_BUILD);
    assertThat(fullBuild.getArtifacts()).hasSize(1);
    InstantRunBuildContext.Artifact artifact = fullBuild.getArtifacts().get(0);
    assertThat(artifact.getType()).isEqualTo(InstantRunBuildContext.FileType.MAIN);
    assertThat(artifact.getLocation().exists()).isTrue();

    ApkSubject apkSubject = expect.about(ApkSubject.FACTORY).that(artifact.getLocation());
    apkSubject.contains("instant-run.zip");
    assertThat(apkSubject.hasMainDexFile());

    // now perform a hot swap test.
    File mainClasses = new File(mProject.getTestDir(), "jars/main/classes.jar");
    assertThat(mainClasses.exists()).isTrue();

    File originalFile = new File(mainClasses.getParentFile(), "original_classes.jar");
    assertThat(mainClasses.renameTo(originalFile)).isTrue();

    try (JarFile inputJar = new JarFile(originalFile);
            JarOutputStream jarOutputFile = new JarOutputStream(new BufferedOutputStream(
                    new FileOutputStream(new File(mainClasses.getParentFile(), "classes.jar"))))) {
        Enumeration<JarEntry> entries = inputJar.entries();
        while (entries.hasMoreElements()) {
            JarEntry element = entries.nextElement();
            try (InputStream inputStream = new BufferedInputStream(inputJar.getInputStream(element))) {
                if (!element.isDirectory()) {
                    jarOutputFile.putNextEntry(new ZipEntry(element.getName()));
                    try {
                        if (element.getName().contains("MainActivity.class")) {
                            // perform hot swap change
                            byte[] classBytes = new byte[(int) element.getSize()];
                            ByteStreams.readFully(inputStream, classBytes);
                            classBytes = hotswapChange(classBytes);
                            jarOutputFile.write(classBytes);
                        } else {
                            ByteStreams.copy(inputStream, jarOutputFile);
                        }//w w w.  jav a 2 s. c o  m
                    } finally {
                        jarOutputFile.closeEntry();
                    }
                }
            }
        }
    }

    mProject.executor().withInstantRun(23, ColdswapMode.AUTO).withPackaging(mPackaging).run("process");

    instantRunBuildContext = loadFromBuildInfo();
    assertThat(instantRunBuildContext.getPreviousBuilds()).hasSize(2);
    InstantRunBuildContext.Build lastBuild = instantRunBuildContext.getLastBuild();
    assertThat(lastBuild).isNotNull();
    assertThat(lastBuild.getVerifierStatus().isPresent());
    assertThat(lastBuild.getVerifierStatus().get()).isEqualTo(InstantRunVerifierStatus.COMPATIBLE);
    assertThat(lastBuild.getArtifacts()).hasSize(1);
    artifact = lastBuild.getArtifacts().get(0);
    assertThat(artifact.getType()).isEqualTo(InstantRunBuildContext.FileType.RELOAD_DEX);
    assertThat(artifact.getLocation()).isNotNull();
    File dexFile = artifact.getLocation();
    assertThat(dexFile.exists()).isTrue();
    DexFileSubject reloadDex = expect.about(DexFileSubject.FACTORY).that(dexFile);
    reloadDex.hasClass("Lcom/android/tools/fd/runtime/AppPatchesLoaderImpl;").that();
    reloadDex.hasClass("Lcom/example/jedo/blazeapp/MainActivity$override;").that();
}

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

/**
 * Extracts the contents of the job pack and registers the included jobs with
 * the SLAMD server.// w w w.j  av a 2 s. c om
 *
 * @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:com.googlecode.onevre.utils.ServerClassLoader.java

/**
 *
 * @see java.lang.ClassLoader#findLibrary(java.lang.String)
 *//*w  w  w. ja va2s  . c  om*/
protected String findLibrary(String libname) {
    try {
        String name = System.mapLibraryName(libname + "-" + System.getProperty("os.arch"));
        URL url = getResourceURL(name);
        log.info("Loading " + name + " from " + url);
        if (url != null) {
            File jar = cachedJars.get(url);
            JarFile jarFile = new JarFile(jar);
            JarEntry entry = jarFile.getJarEntry(name);
            File library = new File(localLibDirectory, name);
            if (!library.exists()) {
                InputStream input = jarFile.getInputStream(entry);
                FileOutputStream output = new FileOutputStream(library);
                byte[] buffer = new byte[BUFFER_SIZE];
                int totalBytes = 0;
                while (totalBytes < entry.getSize()) {
                    int bytesRead = input.read(buffer);
                    if (bytesRead < 0) {
                        throw new IOException("Jar Entry too short!");
                    }
                    output.write(buffer, 0, bytesRead);
                    totalBytes += bytesRead;
                }
                output.close();
                input.close();
                jarFile.close();
            }
            return library.getAbsolutePath();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.flexive.shared.FxSharedUtils.java

/**
 * Reads the content of a given entry in a Jar file (JarInputStream) and returns it as a String
 *
 * @param jarStream the given JarInputStream
 * @param entry     the given entry in the jar file
 * @return the entry's content as a String
 * @throws java.io.IOException on errors
 */// w  w w .  j av  a2s . c o  m
public static String readFromJarEntry(JarInputStream jarStream, JarEntry entry) throws IOException {
    final String fileContent;
    if (entry.getSize() >= 0) {
        // allocate buffer for the entire (uncompressed) script code
        final byte[] buffer = new byte[(int) entry.getSize()];
        // decompress JAR entry
        int offset = 0;
        int readBytes;
        while ((readBytes = jarStream.read(buffer, offset, (int) entry.getSize() - offset)) > 0) {
            offset += readBytes;
        }
        if (offset != entry.getSize()) {
            throw new IOException("Failed to read complete script code for script: " + entry.getName());
        }
        fileContent = new String(buffer, "UTF-8").trim();
    } else {
        // use this method if the file size cannot be determined
        //(might be the case with jar files created with some jar tools)
        final StringBuilder out = new StringBuilder();
        final byte[] buf = new byte[1024];
        int readBytes;
        while ((readBytes = jarStream.read(buf, 0, buf.length)) > 0) {
            out.append(new String(buf, 0, readBytes, "UTF-8"));
        }
        fileContent = out.toString();
    }
    return fileContent;
}

From source file:JNLPAppletLauncher.java

/**
 * Check the native certificates with the ones in the jar file containing the
 * certificates for the JNLPAppletLauncher class (all must match).
 *//*from www. j  a v a 2 s. co  m*/
private boolean checkNativeCertificates(JarFile jar, JarEntry entry, byte[] buf) throws IOException {

    // API states that we must read all of the data from the entry's
    // InputStream in order to be able to get its certificates

    InputStream is = jar.getInputStream(entry);
    int totalLength = (int) entry.getSize();
    int len;
    while ((len = is.read(buf)) > 0) {
    }
    is.close();

    // locate JNLPAppletLauncher certificates
    Certificate[] appletLauncherCerts = JNLPAppletLauncher.class.getProtectionDomain().getCodeSource()
            .getCertificates();
    if (appletLauncherCerts == null || appletLauncherCerts.length == 0) {
        throw new IOException("Cannot find certificates for JNLPAppletLauncher class");
    }

    // Get the certificates for the JAR entry
    Certificate[] nativeCerts = entry.getCertificates();
    if (nativeCerts == null || nativeCerts.length == 0) {
        return false;
    }

    int checked = 0;
    for (int i = 0; i < appletLauncherCerts.length; i++) {
        for (int j = 0; j < nativeCerts.length; j++) {
            if (nativeCerts[j].equals(appletLauncherCerts[i])) {
                checked++;
                break;
            }
        }
    }
    return (checked == appletLauncherCerts.length);
}

From source file:org.apache.catalina.loader.WebappClassLoader.java

/**
 * Find specified resource in local repositories.
 *
 * @return the loaded resource, or null if the resource isn't found
 *///from   www . j a  v  a  2s  . c o  m
protected ResourceEntry findResourceInternal(String name, String path) {

    if (!started) {
        log.info(sm.getString("webappClassLoader.stopped"));
        return null;
    }

    if ((name == null) || (path == null))
        return null;

    ResourceEntry entry = (ResourceEntry) resourceEntries.get(name);
    if (entry != null)
        return entry;

    int contentLength = -1;
    InputStream binaryStream = null;

    int jarFilesLength = jarFiles.length;
    int repositoriesLength = repositories.length;

    int i;

    Resource resource = null;

    for (i = 0; (entry == null) && (i < repositoriesLength); i++) {
        try {

            String fullPath = repositories[i] + path;

            Object lookupResult = resources.lookup(fullPath);
            if (lookupResult instanceof Resource) {
                resource = (Resource) lookupResult;
            }

            // Note : Not getting an exception here means the resource was
            // found
            if (securityManager != null) {
                PrivilegedAction dp = new PrivilegedFindResource(files[i], path);
                entry = (ResourceEntry) AccessController.doPrivileged(dp);
            } else {
                entry = findResourceInternal(files[i], path);
            }

            ResourceAttributes attributes = (ResourceAttributes) resources.getAttributes(fullPath);
            contentLength = (int) attributes.getContentLength();
            entry.lastModified = attributes.getLastModified();

            if (resource != null) {

                try {
                    binaryStream = resource.streamContent();
                } catch (IOException e) {
                    return null;
                }

                // Register the full path for modification checking
                // Note: Only syncing on a 'constant' object is needed
                synchronized (allPermission) {

                    int j;

                    long[] result2 = new long[lastModifiedDates.length + 1];
                    for (j = 0; j < lastModifiedDates.length; j++) {
                        result2[j] = lastModifiedDates[j];
                    }
                    result2[lastModifiedDates.length] = entry.lastModified;
                    lastModifiedDates = result2;

                    String[] result = new String[paths.length + 1];
                    for (j = 0; j < paths.length; j++) {
                        result[j] = paths[j];
                    }
                    result[paths.length] = fullPath;
                    paths = result;

                }

            }

        } catch (NamingException e) {
        }
    }

    if ((entry == null) && (notFoundResources.containsKey(name)))
        return null;

    JarEntry jarEntry = null;

    synchronized (jarFiles) {

        openJARs();
        for (i = 0; (entry == null) && (i < jarFilesLength); i++) {

            jarEntry = jarFiles[i].getJarEntry(path);

            if (jarEntry != null) {

                entry = new ResourceEntry();
                try {
                    entry.codeBase = getURL(jarRealFiles[i]);
                    String jarFakeUrl = getURI(jarRealFiles[i]).toString();
                    jarFakeUrl = "jar:" + jarFakeUrl + "!/" + path;
                    entry.source = new URL(jarFakeUrl);
                    entry.lastModified = jarRealFiles[i].lastModified();
                } catch (MalformedURLException e) {
                    return null;
                }
                contentLength = (int) jarEntry.getSize();
                try {
                    entry.manifest = jarFiles[i].getManifest();
                    binaryStream = jarFiles[i].getInputStream(jarEntry);
                } catch (IOException e) {
                    return null;
                }

                // Extract resources contained in JAR to the workdir
                if (!(path.endsWith(".class"))) {
                    byte[] buf = new byte[1024];
                    File resourceFile = new File(loaderDir, jarEntry.getName());
                    if (!resourceFile.exists()) {
                        Enumeration entries = jarFiles[i].entries();
                        while (entries.hasMoreElements()) {
                            JarEntry jarEntry2 = (JarEntry) entries.nextElement();
                            if (!(jarEntry2.isDirectory()) && (!jarEntry2.getName().endsWith(".class"))) {
                                resourceFile = new File(loaderDir, jarEntry2.getName());
                                // No need to check mkdirs result because an
                                // IOException will occur anyway
                                resourceFile.getParentFile().mkdirs();
                                FileOutputStream os = null;
                                InputStream is = null;
                                try {
                                    is = jarFiles[i].getInputStream(jarEntry2);
                                    os = new FileOutputStream(resourceFile);
                                    while (true) {
                                        int n = is.read(buf);
                                        if (n <= 0) {
                                            break;
                                        }
                                        os.write(buf, 0, n);
                                    }
                                } catch (IOException e) {
                                    // Ignore
                                } finally {
                                    try {
                                        if (is != null) {
                                            is.close();
                                        }
                                    } catch (IOException e) {
                                    }
                                    try {
                                        if (os != null) {
                                            os.close();
                                        }
                                    } catch (IOException e) {
                                    }
                                }
                            }
                        }
                    }
                }

            }

        }

        if (entry == null) {
            synchronized (notFoundResources) {
                notFoundResources.put(name, name);
            }
            return null;
        }

        if (binaryStream != null) {

            byte[] binaryContent = new byte[contentLength];

            try {
                int pos = 0;

                while (true) {
                    int n = binaryStream.read(binaryContent, pos, binaryContent.length - pos);
                    if (n <= 0)
                        break;
                    pos += n;
                }
                binaryStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }

            entry.binaryContent = binaryContent;

            // The certificates are only available after the JarEntry 
            // associated input stream has been fully read
            if (jarEntry != null) {
                entry.certificates = jarEntry.getCertificates();
            }

        }

    }

    // Add the entry in the local resource repository
    synchronized (resourceEntries) {
        // Ensures that all the threads which may be in a race to load
        // a particular class all end up with the same ResourceEntry
        // instance
        ResourceEntry entry2 = (ResourceEntry) resourceEntries.get(name);
        if (entry2 == null) {
            resourceEntries.put(name, entry);
        } else {
            entry = entry2;
        }
    }

    return entry;

}

From source file:org.apache.pluto.util.assemble.ear.EarAssembler.java

private AssemblySink getByteArrayAssemblySink(JarEntry entry) {
    // Create a buffer the size of the warfile, plus a little extra, to 
    // account for the additional bytes added to web.xml as a result of
    // assembly./*from   w  w  w  .  ja v  a  2  s  .c om*/

    ByteArrayAssemblySink warBytesOut = null;
    int defaultBuflen = 1024 * 1024 * 10; // 10Mb
    int assemblyBuflen = 1024 * 32; // 32kb additional bytes for assembly

    // ByteArrayOutputStream grows the buffer by a left bitshift each time
    // its internal buffer would overflow.  The goal is to prevent the
    // buffer from overflowing, otherwise the exponential growth of
    // the internal buffer can cause OOM errors.

    // note that we can only optimize the buffer for file sizes less than 
    // Integer.MAX_VALUE - assemblyBuf
    if (entry.getSize() > (Integer.MAX_VALUE - assemblyBuflen) || entry.getSize() < 1) {
        warBytesOut = new ByteArrayAssemblySink(new ByteArrayOutputStream(defaultBuflen));
    } else {
        int buflen = (int) entry.getSize() + assemblyBuflen;
        warBytesOut = new ByteArrayAssemblySink(new ByteArrayOutputStream(buflen));
    }

    return warBytesOut;
}

From source file:org.apache.pluto.util.assemble.io.JarStreamingAssembly.java

private static JarEntry smartClone(JarEntry originalJarEntry) {
    final JarEntry newJarEntry = new JarEntry(originalJarEntry.getName());
    newJarEntry.setComment(originalJarEntry.getComment());
    newJarEntry.setExtra(originalJarEntry.getExtra());
    newJarEntry.setMethod(originalJarEntry.getMethod());
    newJarEntry.setTime(originalJarEntry.getTime());

    //Must set size and CRC for STORED entries
    if (newJarEntry.getMethod() == ZipEntry.STORED) {
        newJarEntry.setSize(originalJarEntry.getSize());
        newJarEntry.setCrc(originalJarEntry.getCrc());
    }// w w w.  ja v  a 2 s  .  c o m

    return newJarEntry;
}

From source file:org.apache.sling.maven.slingstart.PreparePackageMojoTest.java

private static void compareJarContents(File orgJar, File actualJar) throws IOException {
    try (JarInputStream jis1 = new JarInputStream(new FileInputStream(orgJar));
            JarInputStream jis2 = new JarInputStream(new FileInputStream(actualJar))) {
        JarEntry je1 = null;
        while ((je1 = jis1.getNextJarEntry()) != null) {
            if (je1.isDirectory())
                continue;

            JarEntry je2 = null;/*from ww w.  j a  v a2s  .  co  m*/
            while ((je2 = jis2.getNextJarEntry()) != null) {
                if (!je2.isDirectory())
                    break;
            }

            assertEquals(je1.getName(), je2.getName());
            assertEquals(je1.getSize(), je2.getSize());

            try {
                byte[] buf1 = IOUtils.toByteArray(jis1);
                byte[] buf2 = IOUtils.toByteArray(jis2);

                assertArrayEquals("Contents not equal: " + je1.getName(), buf1, buf2);
            } finally {
                jis1.closeEntry();
                jis2.closeEntry();
            }
        }
    }
}

From source file:org.jahia.modules.serversettings.portlets.BasePortletHelper.java

static JarEntry cloneEntry(JarEntry originalJarEntry) {
    final JarEntry newJarEntry = new JarEntry(originalJarEntry.getName());
    newJarEntry.setComment(originalJarEntry.getComment());
    newJarEntry.setExtra(originalJarEntry.getExtra());
    newJarEntry.setMethod(originalJarEntry.getMethod());
    newJarEntry.setTime(originalJarEntry.getTime());

    // Must set size and CRC for STORED entries
    if (newJarEntry.getMethod() == ZipEntry.STORED) {
        newJarEntry.setSize(originalJarEntry.getSize());
        newJarEntry.setCrc(originalJarEntry.getCrc());
    }//from www.j a v a 2 s.c om

    return newJarEntry;
}