Search in sources :

Example 1 with ZipException

use of java.util.zip.ZipException in project storm by apache.

the class DefaultShader method addRemappedClass.

private void addRemappedClass(RelocatorRemapper remapper, JarOutputStream jos, String name, InputStream is) throws IOException {
    LOG.debug("Remapping class... " + name);
    if (!remapper.hasRelocators()) {
        try {
            LOG.debug("Just copy class...");
            jos.putNextEntry(new JarEntry(name));
            IOUtil.copy(is, jos);
        } catch (ZipException e) {
            LOG.info("zip exception ", e);
        }
        return;
    }
    ClassReader cr = new ClassReader(is);
    // We don't pass the ClassReader here. This forces the ClassWriter to rebuild the constant pool.
    // Copying the original constant pool should be avoided because it would keep references
    // to the original class names. This is not a problem at runtime (because these entries in the
    // constant pool are never used), but confuses some tools such as Felix' maven-bundle-plugin
    // that use the constant pool to determine the dependencies of a class.
    ClassWriter cw = new ClassWriter(0);
    final String pkg = name.substring(0, name.lastIndexOf('/') + 1);
    ClassVisitor cv = new RemappingClassAdapter(cw, remapper) {

        @Override
        public void visitSource(final String source, final String debug) {
            LOG.debug("visitSource " + source);
            if (source == null) {
                super.visitSource(source, debug);
            } else {
                final String fqSource = pkg + source;
                final String mappedSource = remapper.map(fqSource);
                final String filename = mappedSource.substring(mappedSource.lastIndexOf('/') + 1);
                LOG.debug("Remapped to " + filename);
                super.visitSource(filename, debug);
            }
        }
    };
    try {
        cr.accept(cv, ClassReader.EXPAND_FRAMES);
    } catch (Throwable ise) {
        throw new IOException("Error in ASM processing class " + name, ise);
    }
    byte[] renamedClass = cw.toByteArray();
    // Need to take the .class off for remapping evaluation
    String mappedName = remapper.map(name.substring(0, name.indexOf('.')));
    LOG.debug("Remapped class name to " + mappedName);
    try {
        // Now we put it back on so the class file is written out with the right extension.
        jos.putNextEntry(new JarEntry(mappedName + ".class"));
        jos.write(renamedClass);
    } catch (ZipException e) {
        LOG.info("zip exception ", e);
    }
}
Also used : RemappingClassAdapter(org.objectweb.asm.commons.RemappingClassAdapter) ClassReader(org.objectweb.asm.ClassReader) ZipException(java.util.zip.ZipException) ClassVisitor(org.objectweb.asm.ClassVisitor) JarEntry(java.util.jar.JarEntry) ClassWriter(org.objectweb.asm.ClassWriter)

Example 2 with ZipException

use of java.util.zip.ZipException in project atlas by alibaba.

the class TinkerZipFile method readCentralDir.

/**
     * Find the central directory and read the contents.
     *
     * <p>The central directory can be followed by a variable-length comment
     * field, so we have to scan through it backwards.  The comment is at
     * most 64K, plus we have 18 bytes for the end-of-central-dir stuff
     * itself, plus apparently sometimes people throw random junk on the end
     * just for the fun of it.
     *
     * <p>This is all a little wobbly.  If the wrong value ends up in the EOCD
     * area, we're hosed. This appears to be the way that everybody handles
     * it though, so we're in good company if this fails.
     */
private void readCentralDir() throws IOException {
    // Scan back, looking for the End Of Central Directory field. If the zip file doesn't
    // have an overall comment (unrelated to any per-entry comments), we'll hit the EOCD
    // on the first try.
    // No need to synchronize raf here -- we only do this when we first open the zip file.
    long scanOffset = raf.length() - ENDHDR;
    if (scanOffset < 0) {
        throw new ZipException("File too short to be a zip file: " + raf.length());
    }
    raf.seek(0);
    final int headerMagic = Integer.reverseBytes(raf.readInt());
    if (headerMagic != LOCSIG) {
        throw new ZipException("Not a zip archive");
    }
    long stopOffset = scanOffset - 65536;
    if (stopOffset < 0) {
        stopOffset = 0;
    }
    while (true) {
        raf.seek(scanOffset);
        if (Integer.reverseBytes(raf.readInt()) == ENDSIG) {
            break;
        }
        scanOffset--;
        if (scanOffset < stopOffset) {
            throw new ZipException("End Of Central Directory signature not found");
        }
    }
    // Read the End Of Central Directory. ENDHDR includes the signature bytes,
    // which we've already read.
    byte[] eocd = new byte[ENDHDR - 4];
    raf.readFully(eocd);
    // Pull out the information we need.
    BufferIterator it = HeapBufferIterator.iterator(eocd, 0, eocd.length, ByteOrder.LITTLE_ENDIAN);
    int diskNumber = it.readShort() & 0xffff;
    int diskWithCentralDir = it.readShort() & 0xffff;
    int numEntries = it.readShort() & 0xffff;
    int totalNumEntries = it.readShort() & 0xffff;
    // Ignore centralDirSize.
    it.skip(4);
    long centralDirOffset = ((long) it.readInt()) & 0xffffffffL;
    int commentLength = it.readShort() & 0xffff;
    if (numEntries != totalNumEntries || diskNumber != 0 || diskWithCentralDir != 0) {
        throw new ZipException("Spanned archives not supported");
    }
    if (commentLength > 0) {
        byte[] commentBytes = new byte[commentLength];
        raf.readFully(commentBytes);
        comment = new String(commentBytes, 0, commentBytes.length, StandardCharsets.UTF_8);
    }
    // Seek to the first CDE and read all entries.
    // We have to do this now (from the constructor) rather than lazily because the
    // public API doesn't allow us to throw IOException except from the constructor
    // or from getInputStream.
    RAFStream rafStream = new RAFStream(raf, centralDirOffset);
    BufferedInputStream bufferedStream = new BufferedInputStream(rafStream, 4096);
    // Reuse the same buffer for each entry.
    byte[] hdrBuf = new byte[CENHDR];
    for (int i = 0; i < numEntries; ++i) {
        TinkerZipEntry newEntry = new TinkerZipEntry(hdrBuf, bufferedStream, StandardCharsets.UTF_8, (false));
        if (newEntry.localHeaderRelOffset >= centralDirOffset) {
            throw new ZipException("Local file header offset is after central directory");
        }
        String entryName = newEntry.getName();
        if (entries.put(entryName, newEntry) != null) {
            throw new ZipException("Duplicate entry name: " + entryName);
        }
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) ZipException(java.util.zip.ZipException)

Example 3 with ZipException

use of java.util.zip.ZipException in project cogtool by cogtool.

the class ObjectPersister method load.

// registerForPersistence
/**
     * Load an Object from a file.  This method assumes that all error checking
     * and prompting/correction for the validity of the file has already
     * been completed.
     *
     * @param src the File location of the saved Object
     * @return a new instantiated Object
     * @throws java.io.IOException if any file operation fails or the SAX XML
     *         parser fails
     */
public Object load(File src) throws IOException {
    // See if an object is already loaded for the given file
    String canonicalFileName = src.getCanonicalPath();
    PersistInfo info = getInfoByName(canonicalFileName);
    if (info != null) {
        return info.obj;
    }
    // Attempt to create a file of 3x size in the temp directory
    // to hold the expanded XML serialization.
    File sizeCheckFile = File.createTempFile(tmpFilePrefix, ".size", tmpDir);
    try {
        checkDiskSpace(sizeCheckFile, 3 * src.length(), "Not enough temp space on disk to open file: " + src);
    } finally {
        sizeCheckFile.delete();
    }
    // If we're here, no exception was thrown; create checkpoint directory
    File chkptFile = createTempDirectory();
    // Open file as ZipFile and decompress
    ZipFile zip = null;
    try {
        zip = new ZipFile(src);
        // Unzip the file to the checkpoint directory
        ZipUtil.unzip(zip, chkptFile);
    } catch (ZipException ex) {
        IOException newE = new IOException("load encountered zip compression error");
        newE.initCause(ex);
        throw newE;
    } finally {
        if (zip != null) {
            zip.close();
        }
    }
    // Load object from the expanded XML serialization
    ObjectLoader l = new ObjectLoader();
    Object obj = null;
    Reader reader = null;
    try {
        reader = new InputStreamReader(new FileInputStream(new File(chkptFile, PERSIST_FILE)), "UTF-8");
        Collection<?> objSet = l.load(new InputSource(reader), null);
        // There should be only one top-level object
        Iterator<?> objs = objSet.iterator();
        if (objs.hasNext()) {
            obj = objs.next();
        }
        // Register this file for future lookup, both by object
        // and by file name
        info = new PersistInfo(obj, chkptFile, src);
        objInfos.put(obj, info);
        fileInfos.put(canonicalFileName, info);
    } catch (ParserConfigurationException e) {
        IOException newE = new IOException("load encountered parser error");
        newE.initCause(e);
        throw newE;
    } catch (SAXException e) {
        IOException newE = new IOException("load encountered SAX error");
        newE.initCause(e);
        throw newE;
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
    return obj;
}
Also used : InputSource(org.xml.sax.InputSource) InputStreamReader(java.io.InputStreamReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) FileReader(java.io.FileReader) ZipException(java.util.zip.ZipException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) SAXException(org.xml.sax.SAXException) ZipFile(java.util.zip.ZipFile) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) ZipFile(java.util.zip.ZipFile)

Example 4 with ZipException

use of java.util.zip.ZipException in project tdi-studio-se by Talend.

the class DemoImportTestUtil method getResourceManager.

public static ResourcesManager getResourceManager(DemoProjectBean checkedProjectBean) {
    ResourcesManager resManager = null;
    try {
        Bundle bundle = Platform.getBundle(checkedProjectBean.getPluginId());
        URL demoURL = FileLocator.find(bundle, new Path(checkedProjectBean.getDemoProjectFilePath()), null);
        demoURL = FileLocator.toFileURL(demoURL);
        String filePath = new Path(demoURL.getFile()).toOSString();
        File srcFile = new File(filePath);
        FileResourcesUnityManager fileUnityManager = ResourcesManagerFactory.getInstance().createFileUnityManager(srcFile);
        resManager = fileUnityManager.doUnify();
    } catch (ZipException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TarException e) {
        e.printStackTrace();
    }
    return resManager;
}
Also used : Path(org.eclipse.core.runtime.Path) TarException(org.eclipse.ui.internal.wizards.datatransfer.TarException) Bundle(org.osgi.framework.Bundle) FileNotFoundException(java.io.FileNotFoundException) ResourcesManager(org.talend.repository.items.importexport.manager.ResourcesManager) FileResourcesUnityManager(org.talend.repository.items.importexport.ui.managers.FileResourcesUnityManager) ZipException(java.util.zip.ZipException) IOException(java.io.IOException) File(java.io.File) URL(java.net.URL)

Example 5 with ZipException

use of java.util.zip.ZipException in project ACS by ACS-Community.

the class JarSourceExtractor method extractJavaSourcesToJar.

/**
	 * Extracts Java source files from a JAR file and adds them to another JAR file.
	 * 
	 * @param jarfile  jar file from which Java source will be extracted
	 * @param jarOut  JAR output stream to which the extracted java files will be written;
	 * 					<code>jarOut</code> is left open by this method, so that the client
	 * 					can either call it again, or call <code>jarOut.close()</code> when it's done.
	 * 					(there are problems with re-opening and adding entries to a Jar file.) 
	 * @throws IOException
	 */
public void extractJavaSourcesToJar(JarFile jarfile, JarOutputStream jarOut) throws IOException {
    JarEntry[] javaEntries = getJavaEntries(jarfile);
    if (javaEntries.length > 0) {
        System.out.println("extracting .java from " + jarfile.getName());
        for (int i = 0; i < javaEntries.length; i++) {
            JarEntry javaEntry = javaEntries[i];
            String className = getClassName(javaEntry);
            JarEntry outEntry = new JarEntry(className);
            outEntry.setTime(javaEntry.getTime());
            // write the JarEntry meta-data
            try {
                jarOut.putNextEntry(outEntry);
                // write the entry data
                extract(jarfile, javaEntry, jarOut);
                jarOut.closeEntry();
            } catch (ZipException e) {
                System.err.println("failed to add JarEntry for class '" + className + "' from file '" + jarfile.getName() + "': " + e.toString());
            }
        }
        jarfile.close();
        jarOut.flush();
    } else {
        System.out.println("no .java found in " + jarfile.getName());
    }
}
Also used : ZipException(java.util.zip.ZipException) JarEntry(java.util.jar.JarEntry)

Aggregations

ZipException (java.util.zip.ZipException)194 IOException (java.io.IOException)94 File (java.io.File)72 ZipEntry (java.util.zip.ZipEntry)66 ZipFile (java.util.zip.ZipFile)62 InputStream (java.io.InputStream)47 FileInputStream (java.io.FileInputStream)37 ZipInputStream (java.util.zip.ZipInputStream)26 BufferedInputStream (java.io.BufferedInputStream)21 FileOutputStream (java.io.FileOutputStream)21 JarFile (java.util.jar.JarFile)21 JarEntry (java.util.jar.JarEntry)19 FileNotFoundException (java.io.FileNotFoundException)18 ArrayList (java.util.ArrayList)18 ZipOutputStream (java.util.zip.ZipOutputStream)15 ByteArrayInputStream (java.io.ByteArrayInputStream)14 URL (java.net.URL)14 GZIPInputStream (java.util.zip.GZIPInputStream)11 BufferedOutputStream (java.io.BufferedOutputStream)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7