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:com.arcusys.liferay.vaadinplugin.util.ControlPanelPortletUtil.java

public static String getPortalVaadin6Version() throws IOException {

    JarFile jarFile = new JarFile(get6VersionVaadinJarLocation());

    try {//from   w w  w .  java  2  s  .  c  om
        // Check Vaadin 6 version from manifest
        String manifestVaadinVersion = getManifestVaadin6Version(jarFile);
        if (manifestVaadinVersion != null) {
            return manifestVaadinVersion;
        }
        return null;
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
                log.warn(e);
            }
        }
    }
}

From source file:com.xiovr.unibot.plugin.impl.PluginLoaderImpl.java

private Properties getPluginProps(File file) throws IOException {
    Properties result = null;//from w w  w  . ja  v a  2s  . com
    JarFile jar = new JarFile(file);
    Enumeration<JarEntry> entries = jar.entries();

    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (entry.getName().equals(PROPERTY_FILE_NAME)) {
            // That's it! Load props
            InputStream is = null;
            try {
                is = jar.getInputStream(entry);
                result = new Properties();
                result.load(is);
            } finally {
                if (is != null)
                    is.close();
            }
        }
    }
    jar.close();
    return result;
}

From source file:com.magnet.tools.tests.MagnetToolStepDefs.java

@Then("^the jar \"([^\"]*)\" should not contain any matches for:$")
public static void and_the_jar_should_not_contain_any_matches_for(String file, List<String> patterns)
        throws Throwable {
    the_file_should_exist(file);/* w  ww.j a  v  a 2  s .c  o  m*/
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(file);
        Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
        StringBuilder matchList = new StringBuilder();
        JarEntry currentEntry;
        while (jarEntryEnumeration.hasMoreElements()) {
            currentEntry = jarEntryEnumeration.nextElement();
            for (String pattern : patterns) {
                if (currentEntry.getName().matches(pattern)) {
                    matchList.append(currentEntry.getName());
                    matchList.append("\n");
                }
            }
        }
        String matchedStrings = matchList.toString();
        Assert.assertTrue("The jar " + file + "contained\n" + matchedStrings, matchedStrings.isEmpty());

    } finally {
        if (null != jarFile) {
            try {
                jarFile.close();
            } catch (Exception e) {
                /* do nothing */ }
        }
    }
}

From source file:de.smartics.maven.plugin.jboss.modules.util.classpath.AbstractProjectClassLoader.java

/**
 * Opens a reader to the class file within the archive.
 *
 * @param className the name of the class to load.
 * @param fileName the name of the class file to load.
 * @param dirName the name of the directory the archive file is located.
 * @return the reader to the source file for the given class in the archive.
 * @throws ClassNotFoundException if the class cannot be found.
 *///from   w  w w  . jav  a 2s .  co m
protected Class<?> loadClassFromLibrary(final String className, final String fileName, final File dirName)
        throws ClassNotFoundException {
    ensurePackageProvided(className);
    try {
        final JarFile jarFile = new JarFile(dirName); // NOPMD
        final JarEntry entry = jarFile.getJarEntry(fileName);
        if (entry != null) {
            InputStream in = null;
            try {
                in = new BufferedInputStream(jarFile.getInputStream(entry));
                final byte[] data = IOUtils.toByteArray(in);
                final Class<?> clazz = defineClass(className, data, 0, data.length);
                return clazz;
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } catch (final IOException e) {
        final String message = "Cannot load class '" + className + "' from file '" + dirName + "'.";
        LOG.fine(message);

        throw new ClassNotFoundException(message, e);
    }

    final String message = "Cannot load class '" + className + "' from file '" + dirName + "'.";
    LOG.fine(message);

    throw new ClassNotFoundException(message);
}

From source file:com.egreen.tesla.server.api.component.Component.java

private void init() throws FileNotFoundException, IOException, ConfigurationException {

    //Init url/*from   www . java  2  s. c  o  m*/
    this.jarFile = new URL("jar", "", "file:" + file.getAbsolutePath() + "!/");

    final FileInputStream fileInputStream = new FileInputStream(file);
    JarInputStream jarFile = new JarInputStream(fileInputStream);
    JarFile jf = new JarFile(file);

    setConfiguraton(jf);//Configuration load

    jf.getEntry(TESLAR_WIDGET_MAINIFIESTXML);

    JarEntry jarEntry;

    while (true) {
        jarEntry = jarFile.getNextJarEntry();
        if (jarEntry == null) {
            break;
        }
        if (jarEntry.getName().endsWith(".class") && !jarEntry.getName().contains("$")) {
            final String JarNameClass = jarEntry.getName().replaceAll("/", "\\.");
            String className = JarNameClass.replace(".class", "");
            LOGGER.info(className);
            controllerClassMapper.put(className, className);

        } else if (jarEntry.getName().startsWith("webapp")) {
            final String JarNameClass = jarEntry.getName();
            LOGGER.info(JarNameClass);
            saveEntry(jf.getInputStream(jarEntry), JarNameClass);
        }
    }
}

From source file:com.qualogy.qafe.web.css.util.CssProvider.java

private Map<String, InputStream> findResourceInFile(File resourceFile, String fileNamePattern)
        throws IOException {
    Map<String, InputStream> result = new TreeMap<String, InputStream>();
    if (resourceFile.canRead() && resourceFile.getAbsolutePath().endsWith(".jar")) {
        JarFile jarFile = new JarFile(resourceFile);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry singleEntry = entries.nextElement();
            if (singleEntry.getName().matches(fileNamePattern)) {
                result.put(jarFile.getName() + "/" + singleEntry.getName(),
                        jarFile.getInputStream(singleEntry));
            }//from w  ww .  ja v a 2 s  .co m
        }
    }
    return result;
}

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

public static void setupSolrCloudConfigsets(String zkHost) {
    // before anything else, try to get a zookeeper client
    CloudSolrClient zkClient = new CloudSolrClient(zkHost);

    // get resources and copy them to a temporary directory
    Path databaseDir = null;//from w  w  w  . j  ava 2  s . c  o m
    Path tableDir = null;
    Path savedSearchesDir = null;
    try {
        final File jarFile = new File(
                SolrManager.class.getProtectionDomain().getCodeSource().getLocation().toURI());

        // if it is a directory the application in being run from an IDE
        // in that case do not setup (assuming setup is done)
        if (!jarFile.isDirectory()) {
            databaseDir = Files.createTempDirectory("dbv_db_");
            tableDir = Files.createTempDirectory("dbv_tab_");
            savedSearchesDir = Files.createTempDirectory("dbv_tab_");
            final JarFile jar = new JarFile(jarFile);
            final Enumeration<JarEntry> entries = jar.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();

                String nameWithoutOriginPart = null;
                Path destination = null;
                if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_DATABASE_RESOURCE + "/")) {
                    nameWithoutOriginPart = name
                            .substring(ViewerSafeConstants.SOLR_CONFIGSET_DATABASE_RESOURCE.length() + 1);
                    destination = databaseDir;
                } else if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_TABLE_RESOURCE + "/")) {
                    nameWithoutOriginPart = name
                            .substring(ViewerSafeConstants.SOLR_CONFIGSET_TABLE_RESOURCE.length() + 1);
                    destination = tableDir;
                } else if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES_RESOURCE + "/")) {
                    nameWithoutOriginPart = name
                            .substring(ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES_RESOURCE.length() + 1);
                    destination = savedSearchesDir;
                } else {
                    continue;
                }

                Path output = destination.resolve(nameWithoutOriginPart);
                if (name.endsWith("/")) {
                    Files.createDirectories(output);
                } else {
                    InputStream inputStream = SolrManager.class.getResourceAsStream("/" + name);
                    output = Files.createFile(output);
                    OutputStream outputStream = Files.newOutputStream(output, StandardOpenOption.CREATE,
                            StandardOpenOption.WRITE);
                    IOUtils.copy(inputStream, outputStream);
                    inputStream.close();
                    outputStream.close();
                }
            }
            jar.close();
        }
    } catch (IOException | URISyntaxException e) {
        LOGGER.error("Could not extract Solr configset", e);
        if (databaseDir != null) {
            try {
                FileUtils.deleteDirectoryRecursive(databaseDir);
            } catch (IOException e1) {
                LOGGER.debug("IO error deleting temporary folder: " + databaseDir, e1);
            }
        }
        if (tableDir != null) {
            try {
                FileUtils.deleteDirectoryRecursive(tableDir);
            } catch (IOException e1) {
                LOGGER.debug("IO error deleting temporary folder: " + tableDir, e1);
            }
        }
        databaseDir = null;
        tableDir = null;
    }

    // copy configurations to solr
    if (databaseDir != null && tableDir != null) {
        try {
            zkClient.uploadConfig(databaseDir, ViewerSafeConstants.SOLR_CONFIGSET_DATABASE);
        } catch (IOException e) {
            LOGGER.debug("IO error uploading database config to solr cloud", e);
        }
        try {
            zkClient.uploadConfig(tableDir, ViewerSafeConstants.SOLR_CONFIGSET_TABLE);
        } catch (IOException e) {
            LOGGER.debug("IO error uploading table config to solr cloud", e);
        }
        try {
            zkClient.uploadConfig(savedSearchesDir, ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES);
        } catch (IOException e) {
            LOGGER.debug("IO error uploading saved searches config to solr cloud", e);
        }

        try {
            FileUtils.deleteDirectoryRecursive(databaseDir);
        } catch (IOException e1) {
            LOGGER.debug("IO error deleting temporary folder: " + databaseDir, e1);
        }
        try {
            FileUtils.deleteDirectoryRecursive(tableDir);
        } catch (IOException e1) {
            LOGGER.debug("IO error deleting temporary folder: " + tableDir, e1);
        }
        try {
            FileUtils.deleteDirectoryRecursive(savedSearchesDir);
        } catch (IOException e1) {
            LOGGER.debug("IO error deleting temporary folder: " + savedSearchesDir, e1);
        }
    }

    try {
        zkClient.close();
    } catch (IOException e) {
        LOGGER.debug("IO error closing connection to solr cloud", e);
    }
}

From source file:com.googlecode.idea.red5.SelectRed5LocationDialog.java

private String getVersion() {
    String home = homeDir.getText();
    if (home.length() == 0) {
        return EMPTY;
    }/* ww w . ja v a 2 s. co  m*/
    @NonNls
    final String pathToRed5Jar = new StringBuilder().append(home).append(separator).append("red5.jar")
            .toString();
    File red5 = new File(pathToRed5Jar);
    if (red5.exists()) {
        try {
            JarFile jar = new JarFile(pathToRed5Jar);
            Manifest manifest = jar.getManifest();
            Attributes attrs = manifest.getAttributes("");
            if (attrs != null) {
                String version = attrs.getValue("Red5-Version");
                if (version.startsWith("0.7")) {
                    logger.debug("Setting to version 0.7.");
                    return VERSION_DOT_SEVEN;
                } else if (version.startsWith("0.6")) {
                    logger.debug("Setting to version 0.6.");
                    return VERSION_DOT_SIX;
                }
            }
        } catch (IOException e) {
            logger.error("No version found! Returning the default.");
        }
    }
    return VERSION_DOT_EIGHT;
}

From source file:org.apache.maven.plugins.shade.resource.ServiceResourceTransformerTest.java

@Test
public void concatenation() throws Exception {
    SimpleRelocator relocator = new SimpleRelocator("org.foo", "borg.foo", null, null);
    List<Relocator> relocators = Lists.<Relocator>newArrayList(relocator);

    String content = "org.foo.Service\n";
    byte[] contentBytes = content.getBytes("UTF-8");
    InputStream contentStream = new ByteArrayInputStream(contentBytes);
    String contentResource = "META-INF/services/org.something.another";

    ServicesResourceTransformer xformer = new ServicesResourceTransformer();
    xformer.processResource(contentResource, contentStream, relocators);
    contentStream.close();//from ww  w .j  a  v  a  2s.  c  o m

    content = "org.blah.Service\n";
    contentBytes = content.getBytes("UTF-8");
    contentStream = new ByteArrayInputStream(contentBytes);
    contentResource = "META-INF/services/org.something.another";

    xformer.processResource(contentResource, contentStream, relocators);
    contentStream.close();

    File tempJar = File.createTempFile("shade.", ".jar");
    tempJar.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(tempJar);
    JarOutputStream jos = new JarOutputStream(fos);
    try {
        xformer.modifyOutputStream(jos, false);
        jos.close();
        jos = null;
        JarFile jarFile = new JarFile(tempJar);
        JarEntry jarEntry = jarFile.getJarEntry(contentResource);
        assertNotNull(jarEntry);
        InputStream entryStream = jarFile.getInputStream(jarEntry);
        try {
            String xformedContent = IOUtils.toString(entryStream, "utf-8");
            // must be two lines, with our two classes.
            String[] classes = xformedContent.split("\r?\n");
            boolean h1 = false;
            boolean h2 = false;
            for (String name : classes) {
                if ("org.blah.Service".equals(name)) {
                    h1 = true;
                } else if ("borg.foo.Service".equals(name)) {
                    h2 = true;
                }
            }
            assertTrue(h1 && h2);
        } finally {
            IOUtils.closeQuietly(entryStream);
            jarFile.close();
        }
    } finally {
        if (jos != null) {
            IOUtils.closeQuietly(jos);
        }
        tempJar.delete();
    }
}

From source file:at.tuwien.minimee.migration.engines.MonitorEngineTOPDefault.java

/**
 * Copies resource file 'from' from destination 'to' and set execution permission.
 * /*  w  w  w .j  a  v a 2 s  .co  m*/
 * @param from
 * @param to
 * @throws Exception
 */
protected void copyFile(String from, String to, String workingDirectory) throws Exception {

    //
    // copy the shell script to the working directory
    //
    URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from);
    File f = new File(monitorCallShellScriptUrl.getFile());
    String directoryPath = f.getAbsolutePath();
    // if the application was created as exploded archive, the absolute path is a real filename
    String fileName = from;
    InputStream in = null;
    if (directoryPath.indexOf(".jar!") > -1) {
        // this class is not in an exploded archive, extract the filename  
        URL urlJar = new URL(
                directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!')));

        JarFile jf = new JarFile(urlJar.getFile());
        JarEntry je = jf.getJarEntry(from);
        fileName = je.getName();
        in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    } else {
        in = new FileInputStream(f);
    }

    File outScriptFile = new File(to);

    FileOutputStream fos = new FileOutputStream(outScriptFile);
    int nextChar;
    while ((nextChar = in.read()) != -1)
        fos.write(nextChar);

    fos.flush();
    fos.close();

    //
    // This seems kind of hard core, but we have to set execution rights for the shell script, 
    // otherwise we wouldn't be allowed to execute it.
    // The Java-way with FilePermission didn't work for some reason.
    //
    try {
        LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor();
        cmdExecutor.setWorkingDirectory(workingDirectory);

        cmdExecutor.runCommand("chmod 777 " + to);
    } catch (Exception e) {
        throw e;
    }
}