Search in sources :

Example 11 with JarInputStream

use of java.util.jar.JarInputStream in project buck by facebook.

the class FakeProjectFilesystem method getJarManifest.

@Override
public Manifest getJarManifest(Path path) throws IOException {
    try (JarInputStream jar = new JarInputStream(newFileInputStream(path))) {
        Manifest result = jar.getManifest();
        if (result != null) {
            return result;
        }
        // JarInputStream will only find the manifest if it's the first entry, but we have code that
        // puts it elsewhere. We must search. Fortunately, this is test code! So we can be slow!
        JarEntry entry;
        while ((entry = jar.getNextJarEntry()) != null) {
            if (JarFile.MANIFEST_NAME.equals(entry.getName())) {
                result = new Manifest();
                result.read(jar);
                return result;
            }
        }
    }
    return null;
}
Also used : JarInputStream(java.util.jar.JarInputStream) Manifest(java.util.jar.Manifest) JarEntry(java.util.jar.JarEntry)

Example 12 with JarInputStream

use of java.util.jar.JarInputStream in project MinecraftForge by MinecraftForge.

the class ClassPatchManager method setup.

public void setup(Side side) {
    Pattern binpatchMatcher = Pattern.compile(String.format("binpatch/%s/.*.binpatch", side.toString().toLowerCase(Locale.ENGLISH)));
    JarInputStream jis;
    try {
        InputStream binpatchesCompressed = getClass().getResourceAsStream("/binpatches.pack.lzma");
        if (binpatchesCompressed == null) {
            FMLRelaunchLog.log(Level.ERROR, "The binary patch set is missing. Either you are in a development environment, or things are not going to work!");
            return;
        }
        LzmaInputStream binpatchesDecompressed = new LzmaInputStream(binpatchesCompressed);
        ByteArrayOutputStream jarBytes = new ByteArrayOutputStream();
        JarOutputStream jos = new JarOutputStream(jarBytes);
        Pack200.newUnpacker().unpack(binpatchesDecompressed, jos);
        jis = new JarInputStream(new ByteArrayInputStream(jarBytes.toByteArray()));
    } catch (Exception e) {
        FMLRelaunchLog.log(Level.ERROR, e, "Error occurred reading binary patches. Expect severe problems!");
        throw Throwables.propagate(e);
    }
    patches = ArrayListMultimap.create();
    do {
        try {
            JarEntry entry = jis.getNextJarEntry();
            if (entry == null) {
                break;
            }
            if (binpatchMatcher.matcher(entry.getName()).matches()) {
                ClassPatch cp = readPatch(entry, jis);
                if (cp != null) {
                    patches.put(cp.sourceClassName, cp);
                }
            } else {
                jis.closeEntry();
            }
        } catch (IOException e) {
        }
    } while (true);
    FMLRelaunchLog.fine("Read %d binary patches", patches.size());
    if (DEBUG)
        FMLRelaunchLog.fine("Patch list :\n\t%s", Joiner.on("\t\n").join(patches.asMap().entrySet()));
    patchedClasses.clear();
}
Also used : Pattern(java.util.regex.Pattern) LzmaInputStream(LZMA.LzmaInputStream) JarInputStream(java.util.jar.JarInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) JarInputStream(java.util.jar.JarInputStream) LzmaInputStream(LZMA.LzmaInputStream) InputStream(java.io.InputStream) JarOutputStream(java.util.jar.JarOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) JarEntry(java.util.jar.JarEntry) IOException(java.io.IOException)

Example 13 with JarInputStream

use of java.util.jar.JarInputStream in project head by mifos.

the class ApplicationInitializer method copyResources.

private void copyResources(ServletContext sc) throws IOException {
    URL protocol = ETLReportDWHelper.class.getClassLoader().getResource("sql/release-upgrades.txt");
    ConfigurationLocator configurationLocator = new ConfigurationLocator();
    String configPath = configurationLocator.getConfigurationDirectory();
    String destinationDirectoryForJobs = configPath + "/ETL/MifosDataWarehouseETL";
    String destinationDirectoryForJar = configPath + "/ETL/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar";
    String destinationDirectoryForReportJobs = configPath + "/uploads/report";
    String pathFromJar = "/WEB-INF/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar";
    String pathFromJobs = "/WEB-INF/MifosDataWarehouseETL/";
    if (File.separatorChar == '\\') {
        destinationDirectoryForJobs = destinationDirectoryForJobs.replaceAll("/", "\\\\");
        destinationDirectoryForJar = destinationDirectoryForJar.replaceAll("/", "\\\\");
        destinationDirectoryForReportJobs = destinationDirectoryForReportJobs.replaceAll("/", "\\\\");
    }
    File directory = new File(destinationDirectoryForJobs);
    directory.mkdirs();
    File jarDest = new File(destinationDirectoryForJar);
    File reportDirectory = new File(destinationDirectoryForReportJobs);
    reportDirectory.mkdirs();
    if (protocol.getProtocol().equals("jar")) {
        FileUtils.cleanDirectory(directory);
        // Mifos WAR
        URL fullPath = sc.getResource(pathFromJar);
        File f = new File(sc.getResource(pathFromJobs).toString().replace("file:", ""));
        for (File fileEntry : f.listFiles()) {
            FileUtils.copyFileToDirectory(fileEntry, directory);
            logger.info("Copy file: " + fileEntry.getName() + " to: " + directory);
        }
        FileUtils.copyURLToFile(fullPath, jarDest);
        logger.info("Copy file: " + fullPath + " to: " + directory);
        String jarPath = "/WEB-INF/lib/mifos-reporting-1.12-SNAPSHOT.jar";
        String jarName = sc.getResource(jarPath).toString().replace("file:", "");
        JarInputStream jarFileStream = new JarInputStream(new FileInputStream(jarName));
        JarEntry jarEntry;
        while (true) {
            jarEntry = jarFileStream.getNextJarEntry();
            if (jarEntry == null) {
                break;
            }
            // Skip irrelevant folders
            String jarEntryName = jarEntry.getName();
            if (!jarEntryName.startsWith("birt/report") && !jarEntryName.startsWith("pentaho")) {
                continue;
            }
            int lastIndexOfDot = jarEntryName.lastIndexOf('.');
            if (lastIndexOfDot != -1 && !jarEntry.isDirectory()) {
                String destinationDirectory = destinationDirectoryForReportJobs;
                String birtReportFolderName = "birt/report";
                if (jarEntryName.startsWith(birtReportFolderName)) {
                    int indexOfLastSlash = jarEntryName.lastIndexOf('/');
                    String folderName = jarEntryName.substring(birtReportFolderName.length(), indexOfLastSlash).replaceAll("/", "");
                    File birtSubFolder = new File(destinationDirectoryForReportJobs + File.separatorChar + folderName);
                    birtSubFolder.mkdirs();
                    destinationDirectory = destinationDirectoryForReportJobs + File.separatorChar + folderName;
                }
                InputStream inputStream = MifosViewerServletContextListener.class.getClassLoader().getResourceAsStream(jarEntryName);
                int lastIndexOfSlash = jarEntryName.lastIndexOf('/');
                String reportFileName = jarEntryName.substring(lastIndexOfSlash + 1);
                File reportFile = new File(destinationDirectory + File.separatorChar + reportFileName);
                FileUtils.copyInputStreamToFile(inputStream, reportFile);
                logger.info("Copy file: " + jarEntryName + " to: " + reportFile);
            }
        }
    } else {
        try {
            // Mifos Cloud Foundry WAR
            URL fullPath = sc.getResource(pathFromJar);
            File f = new File(sc.getRealPath("/") + pathFromJobs);
            if (f.listFiles().equals(null)) {
                throw new NullPointerException();
            }
            FileUtils.cleanDirectory(directory);
            for (File fileEntry : f.listFiles()) {
                FileUtils.copyFileToDirectory(fileEntry, directory);
                logger.info("Copy file: " + fileEntry.getName() + " to: " + directory);
            }
            FileUtils.copyURLToFile(fullPath, jarDest);
            logger.info("Copy file: " + fullPath + " to: " + directory);
            String sourceBirtReportPath = "/report";
            String sourcePentahoReportPath = "/WEB-INF/classes/pentaho";
            File birtReports = new File(sc.getRealPath("/") + sourceBirtReportPath);
            File pentahoReports = new File(sc.getRealPath("/") + sourcePentahoReportPath);
            for (File fileEntry : birtReports.listFiles()) {
                if (fileEntry.isDirectory()) {
                    File destinationDirectory = new File(destinationDirectoryForReportJobs + File.separatorChar + fileEntry.getName());
                    FileUtils.copyDirectory(fileEntry, destinationDirectory);
                    logger.info("Copy directory: " + fileEntry.getName() + " to: " + destinationDirectory);
                    continue;
                }
                FileUtils.copyFileToDirectory(fileEntry, reportDirectory);
                logger.info("Copy file: " + fileEntry.getName() + " to: " + reportDirectory);
            }
            for (File fileEntry : pentahoReports.listFiles()) {
                FileUtils.copyFileToDirectory(fileEntry, reportDirectory);
                logger.info("Copy file: " + fileEntry.getName() + " to: " + reportDirectory);
            }
        } catch (NullPointerException e) {
            // Eclipse
            logger.info("Could not copy Birt/Pentaho report files to Mifos config directory.");
        }
    }
}
Also used : JarInputStream(java.util.jar.JarInputStream) JarInputStream(java.util.jar.JarInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) MifosViewerServletContextListener(org.mifos.reports.MifosViewerServletContextListener) ETLReportDWHelper(org.mifos.framework.components.batchjobs.helpers.ETLReportDWHelper) ConfigurationLocator(org.mifos.framework.util.ConfigurationLocator) JarEntry(java.util.jar.JarEntry) File(java.io.File) URL(java.net.URL) FileInputStream(java.io.FileInputStream)

Example 14 with JarInputStream

use of java.util.jar.JarInputStream in project morphia by mongodb.

the class ReflectionUtils method getFromJARFile.

/**
     * Returns the classes in a package found in a jar
     *
     * @param loader      the ClassLoader to use
     * @param jar         the jar to scan
     * @param packageName the package to scan
     * @param mapSubPackages whether to map the sub-packages while scanning
     * @return the list of classes
     * @throws IOException            thrown if an error is encountered scanning packages
     * @throws ClassNotFoundException thrown if a class can not be found
     */
public static Set<Class<?>> getFromJARFile(final ClassLoader loader, final String jar, final String packageName, final boolean mapSubPackages) throws IOException, ClassNotFoundException {
    final Set<Class<?>> classes = new HashSet<Class<?>>();
    final JarInputStream jarFile = new JarInputStream(new FileInputStream(jar));
    try {
        JarEntry jarEntry;
        do {
            jarEntry = jarFile.getNextJarEntry();
            if (jarEntry != null) {
                String className = jarEntry.getName();
                if (className.endsWith(".class")) {
                    String classPackageName = getPackageName(className);
                    if (classPackageName.equals(packageName) || (mapSubPackages && isSubPackage(classPackageName, packageName))) {
                        className = stripFilenameExtension(className);
                        classes.add(Class.forName(className.replace('/', '.'), true, loader));
                    }
                }
            }
        } while (jarEntry != null);
    } finally {
        jarFile.close();
    }
    return classes;
}
Also used : JarInputStream(java.util.jar.JarInputStream) JarEntry(java.util.jar.JarEntry) FileInputStream(java.io.FileInputStream) HashSet(java.util.HashSet)

Example 15 with JarInputStream

use of java.util.jar.JarInputStream in project mybatis-3 by mybatis.

the class DefaultVFS method list.

@Override
public List<String> list(URL url, String path) throws IOException {
    InputStream is = null;
    try {
        List<String> resources = new ArrayList<String>();
        // First, try to find the URL of a JAR file containing the requested resource. If a JAR
        // file is found, then we'll list child resources by reading the JAR.
        URL jarUrl = findJarForResource(url);
        if (jarUrl != null) {
            is = jarUrl.openStream();
            if (log.isDebugEnabled()) {
                log.debug("Listing " + url);
            }
            resources = listResources(new JarInputStream(is), path);
        } else {
            List<String> children = new ArrayList<String>();
            try {
                if (isJar(url)) {
                    // Some versions of JBoss VFS might give a JAR stream even if the resource
                    // referenced by the URL isn't actually a JAR
                    is = url.openStream();
                    JarInputStream jarInput = new JarInputStream(is);
                    if (log.isDebugEnabled()) {
                        log.debug("Listing " + url);
                    }
                    for (JarEntry entry; (entry = jarInput.getNextJarEntry()) != null; ) {
                        if (log.isDebugEnabled()) {
                            log.debug("Jar entry: " + entry.getName());
                        }
                        children.add(entry.getName());
                    }
                    jarInput.close();
                } else {
                    /*
             * Some servlet containers allow reading from directory resources like a
             * text file, listing the child resources one per line. However, there is no
             * way to differentiate between directory and file resources just by reading
             * them. To work around that, as each line is read, try to look it up via
             * the class loader as a child of the current resource. If any line fails
             * then we assume the current resource is not a directory.
             */
                    is = url.openStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    List<String> lines = new ArrayList<String>();
                    for (String line; (line = reader.readLine()) != null; ) {
                        if (log.isDebugEnabled()) {
                            log.debug("Reader entry: " + line);
                        }
                        lines.add(line);
                        if (getResources(path + "/" + line).isEmpty()) {
                            lines.clear();
                            break;
                        }
                    }
                    if (!lines.isEmpty()) {
                        if (log.isDebugEnabled()) {
                            log.debug("Listing " + url);
                        }
                        children.addAll(lines);
                    }
                }
            } catch (FileNotFoundException e) {
                /*
           * For file URLs the openStream() call might fail, depending on the servlet
           * container, because directories can't be opened for reading. If that happens,
           * then list the directory directly instead.
           */
                if ("file".equals(url.getProtocol())) {
                    File file = new File(url.getFile());
                    if (log.isDebugEnabled()) {
                        log.debug("Listing directory " + file.getAbsolutePath());
                    }
                    if (file.isDirectory()) {
                        if (log.isDebugEnabled()) {
                            log.debug("Listing " + url);
                        }
                        children = Arrays.asList(file.list());
                    }
                } else {
                    // No idea where the exception came from so rethrow it
                    throw e;
                }
            }
            // The URL prefix to use when recursively listing child resources
            String prefix = url.toExternalForm();
            if (!prefix.endsWith("/")) {
                prefix = prefix + "/";
            }
            // Iterate over immediate children, adding files and recursing into directories
            for (String child : children) {
                String resourcePath = path + "/" + child;
                resources.add(resourcePath);
                URL childUrl = new URL(prefix + child);
                resources.addAll(list(childUrl, resourcePath));
            }
        }
        return resources;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
            // Ignore
            }
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) JarInputStream(java.util.jar.JarInputStream) JarInputStream(java.util.jar.JarInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) BufferedReader(java.io.BufferedReader) FileNotFoundException(java.io.FileNotFoundException) JarEntry(java.util.jar.JarEntry) File(java.io.File) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

JarInputStream (java.util.jar.JarInputStream)154 JarEntry (java.util.jar.JarEntry)72 IOException (java.io.IOException)66 FileInputStream (java.io.FileInputStream)63 Manifest (java.util.jar.Manifest)50 File (java.io.File)46 InputStream (java.io.InputStream)45 ZipEntry (java.util.zip.ZipEntry)29 JarOutputStream (java.util.jar.JarOutputStream)27 FileOutputStream (java.io.FileOutputStream)24 ByteArrayInputStream (java.io.ByteArrayInputStream)22 URL (java.net.URL)20 Test (org.junit.Test)20 OutputStream (java.io.OutputStream)13 JarFile (java.util.jar.JarFile)13 BufferedInputStream (java.io.BufferedInputStream)11 ByteArrayOutputStream (java.io.ByteArrayOutputStream)11 ArrayList (java.util.ArrayList)10 Attributes (java.util.jar.Attributes)10 HashSet (java.util.HashSet)8