Search in sources :

Example 36 with JarFile

use of java.util.jar.JarFile in project ACS by ACS-Community.

the class AcsFileFinderTest method testExtractor.

public void testExtractor() throws Exception {
    AcsJarFileFinder jarFinder = new AcsJarFileFinder(m_dirs, m_logger);
    File[] jarFiles = jarFinder.getAllFiles();
    assertNotNull(jarFiles);
    assertTrue(jarFiles.length > 0);
    JarSourceExtractor extractor = new JarSourceExtractor();
    // test writing separate .java files
    // System.getProperty("java.io.tmpdir"
    File tempDir = new File("jsrc");
    if (tempDir.mkdir() == false)
        m_logger.finest("Directory " + tempDir.toString() + " might already exist.");
    for (int i = 0; i < jarFiles.length; i++) {
        JarFile jarFile = new JarFile(jarFiles[i]);
        extractor.extractJavaSourcesToFiles(jarFile, tempDir);
    }
    // test writing a JAR file with all .java inside\
    File targetJarFile = new File(tempDir, "alljava.jar");
    targetJarFile.delete();
    FileOutputStream out = new FileOutputStream(targetJarFile);
    JarOutputStream jarOut = new JarOutputStream(out);
    for (int i = 0; i < jarFiles.length; /*&& i < 20*/
    i++) {
        JarFile jarFile = new JarFile(jarFiles[i]);
        extractor.extractJavaSourcesToJar(jarFile, jarOut);
    }
    jarOut.finish();
    jarOut.close();
}
Also used : FileOutputStream(java.io.FileOutputStream) JarOutputStream(java.util.jar.JarOutputStream) JarFile(java.util.jar.JarFile) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 37 with JarFile

use of java.util.jar.JarFile in project Activiti by Activiti.

the class BarDeploymentListener method canHandle.

public boolean canHandle(File artifact) {
    JarFile jar = null;
    try {
        if (!artifact.getName().endsWith(".bar")) {
            return false;
        }
        jar = new JarFile(artifact);
        // Only handle non OSGi bundles
        Manifest m = jar.getManifest();
        if (m != null && m.getMainAttributes().getValue(new Attributes.Name(BUNDLE_SYMBOLICNAME)) != null && m.getMainAttributes().getValue(new Attributes.Name(BUNDLE_VERSION)) != null) {
            return false;
        }
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
                LOGGER.error("Unable to close jar", e);
            }
        }
    }
}
Also used : Attributes(java.util.jar.Attributes) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) Manifest(java.util.jar.Manifest) IOException(java.io.IOException)

Example 38 with JarFile

use of java.util.jar.JarFile in project XobotOS by xamarin.

the class PackageParser method collectCertificates.

public boolean collectCertificates(Package pkg, int flags) {
    pkg.mSignatures = null;
    WeakReference<byte[]> readBufferRef;
    byte[] readBuffer = null;
    synchronized (mSync) {
        readBufferRef = mReadBuffer;
        if (readBufferRef != null) {
            mReadBuffer = null;
            readBuffer = readBufferRef.get();
        }
        if (readBuffer == null) {
            readBuffer = new byte[8192];
            readBufferRef = new WeakReference<byte[]>(readBuffer);
        }
    }
    try {
        JarFile jarFile = new JarFile(mArchiveSourcePath);
        Certificate[] certs = null;
        if ((flags & PARSE_IS_SYSTEM) != 0) {
            // If this package comes from the system image, then we
            // can trust it...  we'll just use the AndroidManifest.xml
            // to retrieve its signatures, not validating all of the
            // files.
            JarEntry jarEntry = jarFile.getJarEntry(ANDROID_MANIFEST_FILENAME);
            certs = loadCertificates(jarFile, jarEntry, readBuffer);
            if (certs == null) {
                Slog.e(TAG, "Package " + pkg.packageName + " has no certificates at entry " + jarEntry.getName() + "; ignoring!");
                jarFile.close();
                mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
                return false;
            }
            if (DEBUG_JAR) {
                Slog.i(TAG, "File " + mArchiveSourcePath + ": entry=" + jarEntry + " certs=" + (certs != null ? certs.length : 0));
                if (certs != null) {
                    final int N = certs.length;
                    for (int i = 0; i < N; i++) {
                        Slog.i(TAG, "  Public key: " + certs[i].getPublicKey().getEncoded() + " " + certs[i].getPublicKey());
                    }
                }
            }
        } else {
            Enumeration<JarEntry> entries = jarFile.entries();
            final Manifest manifest = jarFile.getManifest();
            while (entries.hasMoreElements()) {
                final JarEntry je = entries.nextElement();
                if (je.isDirectory())
                    continue;
                final String name = je.getName();
                if (name.startsWith("META-INF/"))
                    continue;
                if (ANDROID_MANIFEST_FILENAME.equals(name)) {
                    final Attributes attributes = manifest.getAttributes(name);
                    pkg.manifestDigest = ManifestDigest.fromAttributes(attributes);
                }
                final Certificate[] localCerts = loadCertificates(jarFile, je, readBuffer);
                if (DEBUG_JAR) {
                    Slog.i(TAG, "File " + mArchiveSourcePath + " entry " + je.getName() + ": certs=" + certs + " (" + (certs != null ? certs.length : 0) + ")");
                }
                if (localCerts == null) {
                    Slog.e(TAG, "Package " + pkg.packageName + " has no certificates at entry " + je.getName() + "; ignoring!");
                    jarFile.close();
                    mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
                    return false;
                } else if (certs == null) {
                    certs = localCerts;
                } else {
                    // Ensure all certificates match.
                    for (int i = 0; i < certs.length; i++) {
                        boolean found = false;
                        for (int j = 0; j < localCerts.length; j++) {
                            if (certs[i] != null && certs[i].equals(localCerts[j])) {
                                found = true;
                                break;
                            }
                        }
                        if (!found || certs.length != localCerts.length) {
                            Slog.e(TAG, "Package " + pkg.packageName + " has mismatched certificates at entry " + je.getName() + "; ignoring!");
                            jarFile.close();
                            mParseError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
                            return false;
                        }
                    }
                }
            }
        }
        jarFile.close();
        synchronized (mSync) {
            mReadBuffer = readBufferRef;
        }
        if (certs != null && certs.length > 0) {
            final int N = certs.length;
            pkg.mSignatures = new Signature[certs.length];
            for (int i = 0; i < N; i++) {
                pkg.mSignatures[i] = new Signature(certs[i].getEncoded());
            }
        } else {
            Slog.e(TAG, "Package " + pkg.packageName + " has no certificates; ignoring!");
            mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
            return false;
        }
    } catch (CertificateEncodingException e) {
        Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
        mParseError = PackageManager.INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING;
        return false;
    } catch (IOException e) {
        Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
        mParseError = PackageManager.INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING;
        return false;
    } catch (RuntimeException e) {
        Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
        mParseError = PackageManager.INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION;
        return false;
    }
    return true;
}
Also used : Attributes(java.util.jar.Attributes) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) Manifest(java.util.jar.Manifest) Certificate(java.security.cert.Certificate)

Example 39 with JarFile

use of java.util.jar.JarFile in project jdk8u_jdk by JetBrains.

the class TestWsImport method main.

public static void main(String[] args) throws IOException {
    String javaHome = System.getProperty("java.home");
    if (javaHome.endsWith("jre")) {
        javaHome = new File(javaHome).getParent();
    }
    String wsimport = javaHome + File.separator + "bin" + File.separator + "wsimport";
    if (System.getProperty("os.name").startsWith("Windows")) {
        wsimport = wsimport.concat(".exe");
    }
    Endpoint endpoint = Endpoint.create(new TestService());
    HttpServer httpServer = null;
    try {
        // Manually create HttpServer here using ephemeral address for port
        // so as to not end up with attempt to bind to an in-use port
        httpServer = HttpServer.create(new InetSocketAddress(0), 0);
        HttpContext httpContext = httpServer.createContext("/hello");
        int port = httpServer.getAddress().getPort();
        System.out.println("port = " + port);
        httpServer.start();
        endpoint.publish(httpContext);
        String address = "http://localhost:" + port + "/hello";
        Service service = Service.create(new URL(address + "?wsdl"), new QName("http://test/jaxws/sample/", "TestService"));
        String[] wsargs = { wsimport, "-p", "wstest", "-J-Djavax.xml.accessExternalSchema=all", "-J-Dcom.sun.tools.internal.ws.Invoker.noSystemProxies=true", address + "?wsdl", "-clientjar", "wsjar.jar" };
        ProcessBuilder pb = new ProcessBuilder(wsargs);
        pb.redirectErrorStream(true);
        Process p = pb.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String s = r.readLine();
        while (s != null) {
            System.out.println(s.trim());
            s = r.readLine();
        }
        p.waitFor();
        p.destroy();
        try (JarFile jarFile = new JarFile("wsjar.jar")) {
            for (Enumeration em = jarFile.entries(); em.hasMoreElements(); ) {
                String fileName = em.nextElement().toString();
                if (fileName.contains("\\")) {
                    throw new RuntimeException("\"\\\" character detected in jar file: " + fileName);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    } finally {
        endpoint.stop();
        if (httpServer != null) {
            httpServer.stop(0);
        }
        Path p = Paths.get("wsjar.jar");
        Files.deleteIfExists(p);
        p = Paths.get("wstest");
        if (Files.exists(p)) {
            try {
                Files.walkFileTree(p, new SimpleFileVisitor<Path>() {

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.delete(file);
                        return CONTINUE;
                    }

                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        if (exc == null) {
                            Files.delete(dir);
                            return CONTINUE;
                        } else {
                            throw exc;
                        }
                    }
                });
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) URL(java.net.URL) Endpoint(javax.xml.ws.Endpoint) HttpServer(com.sun.net.httpserver.HttpServer) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Path(java.nio.file.Path) Enumeration(java.util.Enumeration) InputStreamReader(java.io.InputStreamReader) QName(javax.xml.namespace.QName) HttpContext(com.sun.net.httpserver.HttpContext) Service(javax.xml.ws.Service) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) Endpoint(javax.xml.ws.Endpoint) IOException(java.io.IOException) BufferedReader(java.io.BufferedReader) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 40 with JarFile

use of java.util.jar.JarFile in project jdk8u_jdk by JetBrains.

the class DeleteTempJar method realMain.

public static void realMain(String[] args) throws Exception {
    final File zf = File.createTempFile("deletetemp", ".jar");
    zf.deleteOnExit();
    try (FileOutputStream fos = new FileOutputStream(zf);
        JarOutputStream jos = new JarOutputStream(fos)) {
        JarEntry je = new JarEntry("entry");
        jos.putNextEntry(je);
        jos.write("hello, world".getBytes("ASCII"));
    }
    HttpServer server = HttpServer.create(new InetSocketAddress((InetAddress) null, 0), 0);
    HttpContext context = server.createContext("/", new HttpHandler() {

        public void handle(HttpExchange e) {
            try (FileInputStream fis = new FileInputStream(zf)) {
                e.sendResponseHeaders(200, zf.length());
                OutputStream os = e.getResponseBody();
                byte[] buf = new byte[1024];
                int count = 0;
                while ((count = fis.read(buf)) != -1) {
                    os.write(buf, 0, count);
                }
            } catch (Exception ex) {
                unexpected(ex);
            } finally {
                e.close();
            }
        }
    });
    server.start();
    URL url = new URL("jar:http://localhost:" + new Integer(server.getAddress().getPort()).toString() + "/deletetemp.jar!/");
    JarURLConnection c = (JarURLConnection) url.openConnection();
    JarFile f = c.getJarFile();
    check(f.getEntry("entry") != null);
    System.out.println(f.getName());
    server.stop(0);
}
Also used : InetSocketAddress(java.net.InetSocketAddress) JarURLConnection(java.net.JarURLConnection) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) JarOutputStream(java.util.jar.JarOutputStream) JarOutputStream(java.util.jar.JarOutputStream) JarEntry(java.util.jar.JarEntry) JarFile(java.util.jar.JarFile) FileInputStream(java.io.FileInputStream) URL(java.net.URL) FileOutputStream(java.io.FileOutputStream) JarFile(java.util.jar.JarFile) File(java.io.File) InetAddress(java.net.InetAddress)

Aggregations

JarFile (java.util.jar.JarFile)1366 File (java.io.File)720 JarEntry (java.util.jar.JarEntry)616 IOException (java.io.IOException)587 URL (java.net.URL)272 InputStream (java.io.InputStream)271 ZipEntry (java.util.zip.ZipEntry)203 Manifest (java.util.jar.Manifest)186 ArrayList (java.util.ArrayList)158 Test (org.junit.Test)131 JarURLConnection (java.net.JarURLConnection)123 FileOutputStream (java.io.FileOutputStream)122 ZipFile (java.util.zip.ZipFile)121 FileInputStream (java.io.FileInputStream)111 Attributes (java.util.jar.Attributes)110 MalformedURLException (java.net.MalformedURLException)94 Enumeration (java.util.Enumeration)67 JarOutputStream (java.util.jar.JarOutputStream)65 HashSet (java.util.HashSet)58 URLClassLoader (java.net.URLClassLoader)55