Java Code Examples for java.util.jar.JarEntry#getSize()

The following examples show how to use java.util.jar.JarEntry#getSize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EarAssembler.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
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.
    
    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;
}
 
Example 2
Source File: MarvinJarLoader.java    From marvinproject with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @param entry		JarEntry to be read.
 * @returns 		a byte array of the entry�s content.
 */
public byte[] getEntryBytes(JarEntry entry){
	int l_size = (int)entry.getSize();
	byte[] l_arrBuffer = new byte[l_size];
	InputStream l_inputStream;		
	try{
		l_inputStream = jarFile.getInputStream(entry);
		for(int i=0; i<l_size; i++){
			l_arrBuffer[i] = (byte)l_inputStream.read();
		}
	}
	catch(IOException a_expt){
		a_expt.printStackTrace();
	}
	return l_arrBuffer;
}
 
Example 3
Source File: MarvinJarLoader.java    From marvinproject with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Get a Class object from a class inside the Jar file by its name.
 * @param name		class name.
 * @return 			a Class object
 */
public Class<?> getClass(String name){		
	name = name.replace(".class", "");
	eJarEntries = jarFile.entries();
	JarEntry l_entry = null;
	byte[] l_arrBuffer=null;
	while(eJarEntries.hasMoreElements()){
		l_entry = eJarEntries.nextElement();
		if(l_entry.getName().contains(name+".class")){
			l_arrBuffer = getEntryBytes(l_entry);
			Class<?> l_class = super.defineClass(null, l_arrBuffer, 0, (int)l_entry.getSize());
			return l_class;
		}
	}
	return null;		
}
 
Example 4
Source File: MultiReleaseJarProperties.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
protected Class<?> findClass(String name) throws ClassNotFoundException {
    try {
        byte[] b;
        String entryName = name.replace(".", "/") + ".class";
        JarEntry je = jf.getJarEntry(entryName);
        if (je != null) {
            try (InputStream is = jf.getInputStream(je)) {
                b = new byte[(int) je.getSize()];
                is.read(b);
            }
            return defineClass(name, b, 0, b.length);
        }
        throw new ClassNotFoundException(name);
    } catch (IOException x) {
        throw new ClassNotFoundException(x.getMessage());
    }
}
 
Example 5
Source File: ExamineArchiveTask.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
public void execute() throws BuildException {
    try {
    
        JarInputStream jarIn = new JarInputStream( new FileInputStream( archive ) );
        JarEntry entry;
        while ( ( entry = jarIn.getNextJarEntry() ) != null ) {
            String name = entry.getName();
            long crc = entry.getCrc();
            long size = entry.getSize();
            long compressedSize = entry.getCompressedSize();
            int compressMethod = entry.getMethod();
            long timeStamp = entry.getTime();
            int hashCode = entry.hashCode();
            
            StringBuffer out = new StringBuffer();
            
            out.append( "Name: " + name + "\n" );
            out.append( "  Size: "                  + Long.toHexString( size ) + " " );
            out.append( "  Compressed Size: "       + Long.toHexString( compressedSize ) + " " );
            out.append( "  Compression Method: "    + compressMethod + " " );
            out.append( "  Timestamp: "             + Long.toHexString( timeStamp ) + " " );
            out.append( "  HashCode: "              + Integer.toHexString( hashCode ) + " " );
            out.append( "  CRC: "                   + Long.toHexString( crc ) + " " );
            
            System.out.println( out.toString() );
            
        }
    
    } catch ( Exception e ) {
        throw new BuildException( e.getMessage(), e );
    }
    
}
 
Example 6
Source File: Loader.java    From Cafebabe with GNU General Public License v3.0 5 votes vote down vote up
public static HashMap<JarEntry, ClassNode> loadClasses(JarFile jf) {
	HashMap<JarEntry, ClassNode> classes = new HashMap<>();
	Enumeration<JarEntry> entries = jf.entries();

	while (entries.hasMoreElements()) {
		try {
			JarEntry entry = entries.nextElement();
			if (entry.getSize() < 3) {
				continue;
			}
			InputStream stream = jf.getInputStream(entry);

			ByteArrayOutputStream bos = new ByteArrayOutputStream();

			int read = 0;
			byte[] cafebabe = new byte[4];
			stream.read(cafebabe);
			bos.write(cafebabe, 0, 4);
			if (Arrays.equals(bos.toByteArray(), javaMagic)) {
				byte[] buff = new byte[1024];

				while ((read = stream.read(buff)) != -1) {
					bos.write(buff, 0, read);
				}
				byte[] data = bos.toByteArray();
				classes.put(entry, convertToASM(data));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return classes;
}
 
Example 7
Source File: IndexV1Updater.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
private void processDownloadedIndex(File outputFile, String cacheTag)
        throws IOException, IndexUpdater.UpdateException {
    JarFile jarFile = new JarFile(outputFile, true);
    JarEntry indexEntry = (JarEntry) jarFile.getEntry(DATA_FILE_NAME);
    InputStream indexInputStream = new ProgressBufferedInputStream(jarFile.getInputStream(indexEntry),
            processIndexListener, (int) indexEntry.getSize());
    processIndexV1(indexInputStream, indexEntry, cacheTag);
    jarFile.close();
}
 
Example 8
Source File: Preload.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void preloadJarEntry(Object obj) {
  long start, elapsed;
  JarEntry entry = (JarEntry)obj;
  String name = entry.getName();
  int classIndex = name.indexOf(".class");
  if (classIndex != -1) {
    long size = entry.getSize();
    //long compressedSize = entry.getCompressedSize();
    String classFileName = name.replace('/', '.');
    String className = classFileName.substring(0, classIndex);
    preloadClass(className, size);
  }
}
 
Example 9
Source File: Preload.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void preloadJarEntry(Object obj) {
  long start, elapsed;
  JarEntry entry = (JarEntry)obj;
  String name = entry.getName();
  int classIndex = name.indexOf(".class");
  if (classIndex != -1) {
    long size = entry.getSize();
    //long compressedSize = entry.getCompressedSize();
    String classFileName = name.replace('/', '.');
    String className = classFileName.substring(0, classIndex);
    preloadClass(className, size);
  }
}
 
Example 10
Source File: ModulePatcher.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Resource find(String name) throws IOException {
    JarEntry entry = jf.getJarEntry(name);
    if (entry == null)
        return null;

    return new Resource() {
        @Override
        public String getName() {
            return name;
        }
        @Override
        public URL getURL() {
            String encodedPath = ParseUtil.encodePath(name, false);
            try {
                return new URL("jar:" + csURL + "!/" + encodedPath);
            } catch (MalformedURLException e) {
                return null;
            }
        }
        @Override
        public URL getCodeSourceURL() {
            return csURL;
        }
        @Override
        public ByteBuffer getByteBuffer() throws IOException {
            byte[] bytes = getInputStream().readAllBytes();
            return ByteBuffer.wrap(bytes);
        }
        @Override
        public InputStream getInputStream() throws IOException {
            return jf.getInputStream(entry);
        }
        @Override
        public int getContentLength() throws IOException {
            long size = entry.getSize();
            return (size > Integer.MAX_VALUE) ? -1 : (int) size;
        }
    };
}
 
Example 11
Source File: ModulePatcher.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
@Override
public Resource find(String name) throws IOException {
    JarEntry entry = jf.getJarEntry(name);
    if (entry == null)
        return null;

    return new Resource() {
        @Override
        public String getName() {
            return name;
        }
        @Override
        public URL getURL() {
            String encodedPath = ParseUtil.encodePath(name, false);
            try {
                return new URL("jar:" + csURL + "!/" + encodedPath);
            } catch (MalformedURLException e) {
                return null;
            }
        }
        @Override
        public URL getCodeSourceURL() {
            return csURL;
        }
        @Override
        public ByteBuffer getByteBuffer() throws IOException {
            byte[] bytes = getInputStream().readAllBytes();
            return ByteBuffer.wrap(bytes);
        }
        @Override
        public InputStream getInputStream() throws IOException {
            return jf.getInputStream(entry);
        }
        @Override
        public int getContentLength() throws IOException {
            long size = entry.getSize();
            return (size > Integer.MAX_VALUE) ? -1 : (int) size;
        }
    };
}
 
Example 12
Source File: ResourcesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Too large or too small (empty) files are suspicious.
 *  There should be just couple of them: splash image
 */
public void testUnusualFileSize() throws Exception {
    SortedSet<Violation> violations = new TreeSet<Violation>();
    for (File f: org.netbeans.core.startup.Main.getModuleSystem().getModuleJars()) {
        // check JAR files only
        if (!f.getName().endsWith(".jar"))
            continue;
        
        JarFile jar = new JarFile(f);
        Enumeration<JarEntry> entries = jar.entries();
        JarEntry entry;
        BufferedImage img;
        while (entries.hasMoreElements()) {
            entry = entries.nextElement();
            if (entry.isDirectory())
                continue;
            
            long len = entry.getSize();
            if (len >= 0 && len < 10) {
                violations.add(new Violation(entry.getName(), jar.getName(), " is too small ("+len+" bytes)"));
            }
            if (len >= 200 * 1024) {
                violations.add(new Violation(entry.getName(), jar.getName(), " is too large ("+len+" bytes)"));
            }
        }
    }
    if (!violations.isEmpty()) {
        StringBuilder msg = new StringBuilder();
        msg.append("Some files have extreme size ("+violations.size()+"):\n");
        for (Violation viol: violations) {
            msg.append(viol).append('\n');
        }
        fail(msg.toString());
    }
}
 
Example 13
Source File: JarFileArchive.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
private Archive getUnpackedNestedArchive(JarEntry jarEntry) throws IOException {
    String name = jarEntry.getName();
    if (name.lastIndexOf("/") != -1) {
        name = name.substring(name.lastIndexOf("/") + 1);
    }
    File file = new File(getTempUnpackFolder(), name);
    if (!file.exists() || file.length() != jarEntry.getSize()) {
        unpack(jarEntry, file);
    }
    return new JarFileArchive(file, file.toURI().toURL());
}
 
Example 14
Source File: LancherTest.java    From tac with MIT License 5 votes vote down vote up
private Archive getUnpackedNestedArchive(JarEntry jarEntry) throws IOException {
    String name = jarEntry.getName();
    if (name.lastIndexOf("/") != -1) {
        name = name.substring(name.lastIndexOf("/") + 1);
    }
    File file = new File(getTempUnpackFolder(), name);
    if (!file.exists() || file.length() != jarEntry.getSize()) {
        unpack(jarEntry, file);
    }
    return new JarFileArchive(file, file.toURI().toURL());
}
 
Example 15
Source File: BootJarLaucherUtils.java    From tac with MIT License 5 votes vote down vote up
/**
 *
 * @param jarFile
 * @param jarEntry
 * @return
 * @throws IOException
 */
private static Archive getUnpackedNestedArchive(JarFile jarFile, JarEntry jarEntry) throws IOException {
    String name = jarEntry.getName();
    if (name.lastIndexOf("/") != -1) {
        name = name.substring(name.lastIndexOf("/") + 1);
    }
    File file = new File(getTempUnpackFolder(), name);
    if (!file.exists() || file.length() != jarEntry.getSize()) {
        unpack(jarFile, jarEntry, file);
    }
    return new JarFileArchive(file, file.toURI().toURL());
}
 
Example 16
Source File: ResourceManager.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Search the given jar filename for files in 
 * resources with the given file extension.
 * @param set the set to which resource names will be added
 * @param file jar or zip filename
 * @param resourceDirName name of resource directory, e.g. "defaultTools"
 * @param extension file extension to look for
 */
private static void searchJarFile(Set<String> set, File file, String resourceDirName,
		String extension) throws IOException {

	try (JarFile jarFile = new JarFile(file)) {
		Enumeration<JarEntry> entries = jarFile.entries();
		while (entries.hasMoreElements()) {
			JarEntry entry = entries.nextElement();
			if (entry.getSize() == 0) {
				continue;
			}

			String name = entry.getName();

			// the entry must match the pattern "resources/<resourceDirName>/xxx<extension> 
			// where extension may be null and 'xxx' is a filename and not another sub directory
			if (extension != null && !name.endsWith(extension)) {
				continue;
			}

			String startPath = resourceDirName;
			if (!name.startsWith(startPath)) {
				continue;
			}

			// is it a subdir?
			name = name.substring(startPath.length() + 1); // strip off valid path info
			File entryAsFile = new File(name);
			if (entryAsFile.getParent() != null) {
				continue; // the name was a subdir and not simply a file 
			}

			// add the entry; chop off "resources/"
			set.add(entry.getName());
		}
	}
}
 
Example 17
Source File: IndexUpdater.java    From fdroidclient with GNU General Public License v3.0 4 votes vote down vote up
public void processDownloadedFile(File downloadedFile) throws UpdateException {
    InputStream indexInputStream = null;
    try {
        if (downloadedFile == null || !downloadedFile.exists()) {
            throw new UpdateException(downloadedFile + " does not exist!");
        }

        // Due to a bug in Android 5.0 Lollipop, the inclusion of bouncycastle causes
        // breakage when verifying the signature of the downloaded .jar. For more
        // details, check out https://gitlab.com/fdroid/fdroidclient/issues/111.
        FDroidApp.disableBouncyCastleOnLollipop();

        JarFile jarFile = new JarFile(downloadedFile, true);
        JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexUpdater.DATA_FILE_NAME);
        indexInputStream = new ProgressBufferedInputStream(jarFile.getInputStream(indexEntry),
                processIndexListener, (int) indexEntry.getSize());

        // Process the index...
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        final SAXParser parser = factory.newSAXParser();
        final XMLReader reader = parser.getXMLReader();
        final RepoXMLHandler repoXMLHandler = new RepoXMLHandler(repo, createIndexReceiver());
        reader.setContentHandler(repoXMLHandler);
        reader.parse(new InputSource(indexInputStream));

        long timestamp = repoDetailsToSave.getAsLong(RepoTable.Cols.TIMESTAMP);
        if (timestamp < repo.timestamp) {
            throw new UpdateException("index.jar is older that current index! "
                    + timestamp + " < " + repo.timestamp);
        }

        signingCertFromJar = getSigningCertFromJar(indexEntry);

        // JarEntry can only read certificates after the file represented by that JarEntry
        // has been read completely, so verification cannot run until now...
        assertSigningCertFromXmlCorrect();
        commitToDb();
    } catch (SAXException | ParserConfigurationException | IOException e) {
        throw new UpdateException("Error parsing index", e);
    } finally {
        FDroidApp.enableBouncyCastleOnLollipop();
        Utils.closeQuietly(indexInputStream);
        if (downloadedFile != null) {
            if (!downloadedFile.delete()) {
                Log.w(TAG, "Couldn't delete file: " + downloadedFile.getAbsolutePath());
            }
        }
    }
}
 
Example 18
Source File: JarEntryNode.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public long length() {
	JarFile jarFile = getJarFile();
	JarEntry jarEntry = jarFile.getJarEntry(getPath());
	return jarEntry.getSize();
}