Example usage for java.util.jar JarFile JarFile

List of usage examples for java.util.jar JarFile JarFile

Introduction

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

Prototype

public JarFile(File file) throws IOException 

Source Link

Document

Creates a new JarFile to read from the specified File object.

Usage

From source file:kr.ac.kaist.wala.hybridroid.callgraph.AndroidHybridAnalysisScope.java

/**
 * Make AnalysisScope for Android hybrid application. If you want to use
 * DROIDEL as front-end, use setUpDroidelAnalysisScope method instead of
 * this./*from  ww w  .  j av  a 2s.  c  o m*/
 * 
 * @param classpath
 *            the target apk file uri.
 * @param htmls
 *            JavaScript files contained in the scope.
 * @param exclusions
 *            the exclusion file.
 * @param androidLib
 *            the Android framework directory uri.
 * @return AnalysisScope for Android hybrid application.
 * @throws IOException
 */
public static AndroidHybridAnalysisScope setUpAndroidHybridAnalysisScope(String dir, URI classpath,
        Set<URL> htmls, String exclusions, URI... androidLib) throws IOException {
    AndroidHybridAnalysisScope scope;

    scope = new AndroidHybridAnalysisScope();

    File exclusionsFile = new File(exclusions);
    InputStream fs = exclusionsFile.exists() ? new FileInputStream(exclusionsFile)
            : AndroidHybridAppModel.class.getResourceAsStream(exclusions);
    scope.setExclusions(new FileOfClasses(fs));

    scope.setLoaderImpl(ClassLoaderReference.Primordial, "com.ibm.wala.dalvik.classLoader.WDexClassLoaderImpl");

    for (URI al : androidLib) {
        if (al.getPath().endsWith(".dex"))
            scope.addToScope(ClassLoaderReference.Primordial, DexFileModule.make(new File(al)));
        else if (al.getPath().endsWith(".jar"))
            scope.addToScope(ClassLoaderReference.Primordial, new JarFileModule(new JarFile(new File(al))));
        else
            throw new InternalError("Android library must be either dex or jar file: " + al.getPath());
    }

    scope.setLoaderImpl(ClassLoaderReference.Application,
            "com.ibm.wala.dalvik.classLoader.WDexClassLoaderImpl");

    scope.addToScope(ClassLoaderReference.Application, DexFileModule.make(new File(classpath)));

    if (!htmls.isEmpty())
        scope = setUpJsAnalysisScope(dir, scope, htmls);

    fs.close();

    return scope;
}

From source file:io.sightly.tck.TCK.java

TCK() {
    String jarPath = TCK.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    try {/*  w w w  .  j  ava 2  s  .  c  o  m*/
        jarFile = new JarFile(jarPath);
    } catch (IOException e) {
        throw new RuntimeException("Unable to instantiate TCK.", e);
    }
    testDefinitions = new ArrayList<JSONObject>();
}

From source file:es.jamisoft.comun.utils.compression.Jar.java

public void descomprimir(String lsDirDestino) {
    try {//from   ww  w  . j  a  v  a 2 s . c  o  m
        JarFile lzfFichero = new JarFile(isFicheroJar);
        Enumeration lenum = lzfFichero.entries();
        JarArchiveEntry entrada = null;
        InputStream linput;

        for (; lenum.hasMoreElements(); linput.close()) {
            entrada = (JarArchiveEntry) lenum.nextElement();
            linput = lzfFichero.getInputStream(entrada);

            byte labBytes[] = new byte[2048];
            int liLeido = -1;
            String lsRutaDestino = lsDirDestino + File.separator + entrada.getName();

            lsRutaDestino = lsRutaDestino.replace('\\', File.separatorChar);

            File lfRutaCompleta = new File(lsRutaDestino);
            String lsRuta = lfRutaCompleta.getAbsolutePath();
            int liPosSeparator = lsRuta.lastIndexOf(File.separatorChar);

            lsRuta = lsRuta.substring(0, liPosSeparator);

            File ldDir = new File(lsRuta);
            boolean lbCreado = ldDir.mkdirs();

            if (entrada.isDirectory()) {
                continue;
            }

            FileOutputStream loutput = new FileOutputStream(lfRutaCompleta);

            if (entrada.getSize() > 0L) {
                while ((liLeido = linput.read(labBytes, 0, 2048)) != -1) {
                    loutput.write(labBytes, 0, liLeido);
                }
            }

            loutput.flush();
            loutput.close();
        }

        lzfFichero.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.kotcrab.vis.editor.plugin.PluginDescriptor.java

public PluginDescriptor(FileHandle file, Manifest manifest) throws EditorException {
    this.file = file;
    folderName = file.parent().name();//from  ww  w . j ava  2  s  . c om
    libs.addAll(file.parent().child("lib").list());

    Attributes attributes = manifest.getMainAttributes();

    id = attributes.getValue(PLUGIN_ID);
    name = attributes.getValue(PLUGIN_NAME);
    description = attributes.getValue(PLUGIN_DESCRIPTION);
    provider = attributes.getValue(PLUGIN_PROVIDER);
    version = attributes.getValue(PLUGIN_VERSION);
    String comp = attributes.getValue(PLUGIN_COMPATIBILITY);
    String licenseFile = attributes.getValue(PLUGIN_LICENSE);

    if (id == null || name == null || description == null || provider == null || version == null
            || comp == null)
        throw new EditorException("Missing one of required field in plugin manifest, plugin: " + file.name());

    try {
        compatibility = Integer.valueOf(comp);
    } catch (NumberFormatException e) {
        throw new EditorException("Failed to parse compatibility code, value must be integer!", e);
    }

    if (licenseFile != null && !licenseFile.isEmpty()) {
        JarFile jar = null;
        try {
            jar = new JarFile(file.file());
            JarEntry licenseEntry = jar.getJarEntry(licenseFile);
            license = StreamUtils.copyStreamToString(jar.getInputStream(licenseEntry));
        } catch (Exception e) {
            throw new EditorException("Failed to read license file for plugin: " + file.name(), e);
        } finally {
            IOUtils.closeQuietly(jar);
        }
    }
}

From source file:com.android.builder.testing.MockableJarGenerator.java

public void createMockableJar(File input, File output) throws IOException {
    Preconditions.checkState(output.createNewFile(), "Output file [%s] already exists.",
            output.getAbsolutePath());/* www .ja  v a 2 s. c  om*/

    JarFile androidJar = null;
    JarOutputStream outputStream = null;
    try {
        androidJar = new JarFile(input);
        outputStream = new JarOutputStream(new FileOutputStream(output));

        for (JarEntry entry : Collections.list(androidJar.entries())) {
            InputStream inputStream = androidJar.getInputStream(entry);

            if (entry.getName().endsWith(".class")) {
                if (!skipClass(entry.getName().replace("/", "."))) {
                    rewriteClass(entry, inputStream, outputStream);
                }
            } else {
                outputStream.putNextEntry(entry);
                ByteStreams.copy(inputStream, outputStream);
            }

            inputStream.close();
        }
    } finally {
        if (androidJar != null) {
            androidJar.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:com.gnadenheimer.mg.frames.admin.FrameConfigAdmin.java

public FrameConfigAdmin() {
    super("Configuracion", true, //resizable
            true, //closable
            true, //maximizable
            true);//iconifiable
    try {/*from   ww  w.jav  a  2  s . c om*/
        initComponents();

        final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());

        if (jarFile.isFile()) { // Run with JAR file
            final JarFile jar = new JarFile(jarFile);
            final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
            while (entries.hasMoreElements()) {
                final String name = entries.nextElement().getName();
                if (name.startsWith("sql/")) { //filter according to the path
                    cboSqlFiles.addItem("/" + name);
                }
            }
            jar.close();
        } else { // Run with IDE
            final URL url = getClass().getResource("/sql");
            if (url != null) {
                try {
                    final File apps = new File(url.toURI());
                    for (File app : apps.listFiles()) {
                        cboSqlFiles.addItem("/sql/" + app.getName());
                    }
                } catch (URISyntaxException ex) {
                    // never happens
                }
            }
        }
        /*CurrentUser currentUser = CurrentUser.getInstance();
        if (currentUser.getUser().getId() == 9999) {
        cmdReset.setEnabled(true);
        jButton3.setEnabled(true);
        } else {
        cmdReset.setEnabled(false);
        jButton3.setEnabled(false);
        }*/

        /*
                   File[] files = (new File(getClass().getResource("/sql").toURI())).listFiles();
                   for (File f : files) {
        cboSqlFiles.addItem(f.getName());
                   }*/
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage());
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
    }
}

From source file:info.dolezel.fatrat.plugins.helpers.JarClassLoader.java

private static void getPackageVersion(File fo, Map<String, String> rv) throws IOException {
    if (!fo.exists())
        return;/* w ww .  j av a  2  s .  c  o  m*/

    JarFile file = new JarFile(fo);
    Manifest manifest = file.getManifest();
    Attributes attr = manifest.getMainAttributes();

    rv.put(fo.getName(), attr.getValue("Implementation-Version"));
}

From source file:de.knurt.fam.plugin.DefaultPluginResolver.java

private void initPlugins() {
    File pluginDirectory = new File(FamConnector.me().getPluginDirectory());
    if (pluginDirectory.exists() && pluginDirectory.isDirectory() && pluginDirectory.canRead()) {
        File[] files = pluginDirectory.listFiles();
        ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
        for (File file : files) {
            if (file.isFile() && file.getName().toLowerCase().endsWith("jar")) {
                JarFile jar = null;
                try {
                    jar = new JarFile(file.getAbsoluteFile().toString());
                    Enumeration<JarEntry> jarEntries = jar.entries();
                    while (jarEntries.hasMoreElements()) {
                        JarEntry entry = jarEntries.nextElement();
                        if (entry.getName().toLowerCase().endsWith("class")) {
                            String className = entry.getName().replaceAll("/", ".").replaceAll("\\.class$", "");
                            // @SuppressWarnings("resource") // classLoader must not be closed, getting an "IllegalStateException: zip file closed" otherwise
                            URLClassLoader classLoader = new URLClassLoader(new URL[] { file.toURI().toURL() },
                                    currentThreadClassLoader);
                            Class<?> cl = classLoader.loadClass(className);
                            if (this.isPlugin(cl)) {
                                Plugin plugin = (Plugin) cl.newInstance();
                                this.plugins.add(plugin);
                            }/*from   ww  w  .ja v  a 2s.  co  m*/
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091426l);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091424l);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091425l);
                } catch (IOException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091351l);
                } finally {
                    try {
                        jar.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
        for (Plugin plugin : this.plugins) {
            boolean found = false;
            if (this.implementz(plugin.getClass(), RegisterSubmission.class)) {
                if (found == true) {
                    throw new PluginConfigurationException("Found more than one RegisterSubmission classes");
                    // TODO #19 supply a solution Ticket
                }
                this.registerSubmission = (RegisterSubmission) plugin;
                found = true;
            }
        }
        for (Plugin plugin : this.plugins) {
            plugin.start();
        }
    }
    // search plugin
    if (this.registerSubmission == null) {
        this.registerSubmission = new DefaultRegisterSubmission();
    }
}

From source file:hotbeans.support.JarFileHotBeanModuleLoader.java

/**
 * Extracts all the files in the module jar file, including nested jar files. The reason for extracting the complete
 * contents of the jar file (and not just the nested jar files) is to make sure the module jar file isn't locked, and
 * thus may be deleted.//w ww.  j  av  a  2  s  .  c  o  m
 */
private void extractLibs() throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Extracting module jar file '" + moduleJarFile + "'.");

    JarFile jarFile = new JarFile(this.moduleJarFile);
    Enumeration entries = jarFile.entries();
    JarEntry entry;
    String entryName;
    File extractedFile = null;
    FileOutputStream extractedFileOutputStream;

    while (entries.hasMoreElements()) {
        entry = (JarEntry) entries.nextElement();
        if ((entry != null) && (!entry.isDirectory())) {
            entryName = entry.getName();
            if (entryName != null) {
                // if( logger.isDebugEnabled() ) logger.debug("Extracting '" + entryName + "'.");

                // Copy nested jar file to temp dir
                extractedFile = new File(this.tempDir, entryName);
                extractedFile.getParentFile().mkdirs();

                extractedFileOutputStream = new FileOutputStream(extractedFile);
                FileCopyUtils.copy(jarFile.getInputStream(entry), extractedFileOutputStream);
                extractedFileOutputStream = null;

                if ((entryName.startsWith(LIB_PATH)) && (entryName.toLowerCase().endsWith(".jar"))) {
                    // Register nested jar file in "class path"
                    super.addURL(extractedFile.toURI().toURL());
                }
            }
        }
    }

    jarFile.close();
    jarFile = null;

    super.addURL(tempDir.toURI().toURL()); // Add temp dir as class path (note that this must be added after all the
                                           // files have been extracted)

    if (logger.isDebugEnabled())
        logger.debug("Done extracting module jar file '" + moduleJarFile + "'.");
}

From source file:com.netease.hearttouch.hthotfix.patch.PatchGeneratorTransformExecutor.java

public void transformJar(File inputFile, File outputFile) throws IOException {
    final JarFile jar = new JarFile(inputFile);
    final OutputJar outputJar = new OutputJar(outputFile);
    for (final Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) {
        final JarEntry entry = entries.nextElement();
        if (entry.isDirectory()) {
            continue;
        }/*from  www  . j  a va2s .c  o m*/
        final InputStream is = jar.getInputStream(entry);
        try {

            byte[] bytecode = IOUtils.toByteArray(is);
            if (entry.getName().endsWith(".class")) {
                if (extension.getGeneratePatch()) {
                    ClassReader cr = new ClassReader(bytecode);
                    String className = cr.getClassName();
                    if ((hashFileParser != null) && (hashFileParser.isChanged(className, bytecode))) {
                        patchJarHelper.writeClassToDirectory(className,
                                hackInjector.inject(className, bytecode));
                        refScanInstrument.addPatchClassName(className, hackInjector.getLastSuperName());
                    }
                }
                outputJar.writeEntry(entry, bytecode);
            } else {
                outputJar.writeEntry(entry, bytecode);
            }
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    outputJar.close();
}