Example usage for java.util.jar JarFile getEntry

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

Introduction

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

Prototype

public ZipEntry getEntry(String name) 

Source Link

Document

Returns the ZipEntry for the given base entry name or null if not found.

Usage

From source file:au.com.addstar.objects.Plugin.java

/**
 * Adds the Spigot.ver file to the jar//from  ww w.ja  v a 2 s . c o m
 *
 * @param ver
 */
public void addSpigotVer(String ver) {
    if (latestFile == null)
        return;
    File newFile = new File(latestFile.getParentFile(),
            SpigotUpdater.getFormat().format(Calendar.getInstance().getTime()) + "-" + ver + "-s.jar");
    File spigotFile = new File(latestFile.getParentFile(), "spigot.ver");
    if (spigotFile.exists())
        FileUtils.deleteQuietly(spigotFile);
    try {
        JarFile oldjar = new JarFile(latestFile);
        if (oldjar.getEntry("spigot.ver") != null)
            return;
        JarOutputStream tempJarOutputStream = new JarOutputStream(new FileOutputStream(newFile));
        try (Writer wr = new FileWriter(spigotFile); BufferedWriter writer = new BufferedWriter(wr)) {
            writer.write(ver);
            writer.newLine();
        }
        try (FileInputStream stream = new FileInputStream(spigotFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            JarEntry je = new JarEntry(spigotFile.getName());
            tempJarOutputStream.putNextEntry(je);
            while ((bytesRead = stream.read(buffer)) != -1) {
                tempJarOutputStream.write(buffer, 0, bytesRead);
            }
            stream.close();
        }
        Enumeration jarEntries = oldjar.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry entry = (JarEntry) jarEntries.nextElement();
            InputStream entryInputStream = oldjar.getInputStream(entry);
            tempJarOutputStream.putNextEntry(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = entryInputStream.read(buffer)) != -1) {
                tempJarOutputStream.write(buffer, 0, bytesRead);
            }
            entryInputStream.close();
        }
        tempJarOutputStream.close();
        oldjar.close();
        FileUtils.deleteQuietly(latestFile);
        FileUtils.deleteQuietly(spigotFile);
        FileUtils.moveFile(newFile, latestFile);
        latestFile = newFile;

    } catch (ZipException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.jasper.compiler.JspUtil.java

public static InputStream getInputStream(String fname, JarFile jarFile, JspCompilationContext ctxt,
        ErrorDispatcher err) throws JasperException, IOException {

    InputStream in = null;//from  ww w .  j a  v  a 2  s  .  c o m

    if (jarFile != null) {
        String jarEntryName = fname.substring(1, fname.length());
        ZipEntry jarEntry = jarFile.getEntry(jarEntryName);
        if (jarEntry == null) {
            err.jspError("jsp.error.file.not.found", fname);
        }
        in = jarFile.getInputStream(jarEntry);
    } else {
        in = ctxt.getResourceAsStream(fname);
    }

    if (in == null) {
        err.jspError("jsp.error.file.not.found", fname);
    }

    return in;
}

From source file:net.sf.freecol.FreeCol.java

/**
 * Get a stream for the default splash file.
 *
 * Note: Not bothering to check for nulls as this is called in try
 * block that ignores all exceptions./*from www.j  a  v a  2s.  co m*/
 *
 * @param juc The <code>JarURLConnection</code> to extract from.
 * @return A suitable <code>InputStream</code>, or null on error.
 */
private static InputStream getDefaultSplashStream(JarURLConnection juc) throws IOException {
    JarFile jf = juc.getJarFile();
    ZipEntry ze = jf.getEntry(SPLASH_DEFAULT);
    return jf.getInputStream(ze);
}

From source file:org.rhq.maven.plugins.ValidateMojo.java

private void validate(File agentPluginArchive, Set<File> parentPlugins) throws MojoExecutionException {
    JarFile jarFile = null;
    try {/*from w  w  w . j  a v  a2s. c om*/
        jarFile = new JarFile(agentPluginArchive);

        if (jarFile.getEntry("META-INF/rhq-plugin.xml") == null) {
            handleFailure("Descriptor missing");
        }
    } catch (Exception e) {
        handleException(e);
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (Exception e) {
                handleException(e);
            }
        }

    }

    // Run the plugin validator as a forked process
    Process process = null;
    try {
        String pluginValidatorClasspath = buildPluginValidatorClasspath(agentPluginArchive, parentPlugins);
        String javaCommand = buildJavaCommand();
        ProcessBuilder processBuilder = buildProcessBuilder(javaCommand, pluginValidatorClasspath);
        process = processBuilder.start();
        redirectOuput(process);
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            handleFailure("Invalid plugin");
        }
    } catch (Exception e) {
        handleException(e);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}

From source file:org.jvnet.hudson.update_center.LocalHPI.java

@Override
public File resolvePOM() throws IOException {
    JarFile jar = null;
    InputStream in = null;/*  ww  w .j  a va 2s . c  om*/
    OutputStream out = null;
    try {
        jar = new JarFile(jarFile);
        String pomPath = String.format("META-INF/maven/%s/%s/pom.xml", artifact.groupId, artifact.artifactId);
        ZipEntry e = jar.getEntry(pomPath);
        if (e == null) {
            return null;
        }

        File temporaryFile = File.createTempFile(artifact.artifactId, ".xml");
        temporaryFile.deleteOnExit();

        in = jar.getInputStream(e);
        out = new FileOutputStream(temporaryFile);

        IOUtils.copy(in, out);

        return temporaryFile;
    } finally {
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
        if (jar != null) {
            jar.close();
        }
    }
}

From source file:cc.creativecomputing.io.CCIOUtil.java

/**
 * Simplified method to open a Java InputStream.
 * <p>//from ww  w .j a va 2 s.  c  o  m
 * This method is useful if you want to easily open things from the data folder or from a URL, but want an
 * InputStream object so that you can use other Java methods to take more control of how the stream is read.
 * </p>
 * <p>
 * If the requested item doesn't exist, null is returned. This will also check to see if the user is asking for a
 * file whose name isn't properly capitalized. It is strongly recommended that libraries use this method to open
 * data files, so that the loading sequence is handled in the same way.
 * </p>
 * 
 * @param theFilename The filename passed in can be:
 *        <ul>
 *        <li>An URL, for instance openStream("http://creativecomputing.cc/");</li>
 *        <li>A file in the application's data folder</li>
 *        <li>Another file to be opened locally</li>
 *        </ul>
 */
static public InputStream createStream(String theFilename) {
    InputStream stream = null;

    // check if the filename makes sense
    if (theFilename == null || theFilename.length() == 0)
        return null;

    // safe to check for this as a url first. this will prevent online
    try {
        URL urlObject = new URL(theFilename);
        URLConnection con = urlObject.openConnection();
        // try to be a browser some sources do not like bots
        con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)");
        return con.getInputStream();
    } catch (MalformedURLException mfue) {
        // not a url, that's fine
    } catch (FileNotFoundException fnfe) {
        // Java 1.5 likes to throw this when URL not available.

    } catch (IOException e) {
        return null;
    }

    // load resource from jar using the path with getResourceAsStream
    if (theFilename.contains(".jar!")) {
        String[] myParts = theFilename.split("!");
        String myJarPath = myParts[0];
        if (myJarPath.startsWith("file:")) {
            myJarPath = myJarPath.substring(5);
        }

        String myFilePath = myParts[1];
        if (myFilePath.startsWith("/")) {
            myFilePath = myFilePath.substring(1);
        }
        try {
            @SuppressWarnings("resource")
            JarFile myJarFile = new JarFile(myJarPath);
            return myJarFile.getInputStream(myJarFile.getEntry(myFilePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // handle case sensitivity check
    try {
        // first see if it's in a data folder
        File file = dataFile(theFilename);
        if (!file.exists()) {
            // next see if it's just in this folder
            file = new File(CCSystem.applicationPath, theFilename);
        }
        if (file.exists()) {
            try {
                String filePath = file.getCanonicalPath();
                String filenameActual = new File(filePath).getName();
                // make sure there isn't a subfolder prepended to the name
                String filenameShort = new File(theFilename).getName();
                // if the actual filename is the same, but capitalized
                // differently, warn the user.
                //if (filenameActual.equalsIgnoreCase(filenameShort) &&
                //!filenameActual.equals(filenameShort)) {
                if (!filenameActual.equals(filenameShort)) {
                    throw new RuntimeException("This file is named " + filenameActual + " not " + theFilename
                            + ". Re-name it " + "or change your code.");
                }
            } catch (IOException e) {
            }
        }

        // if this file is ok, may as well just load it
        stream = new FileInputStream(file);
        if (stream != null)
            return stream;

        // have to break these out because a general Exception might
        // catch the RuntimeException being thrown above
    } catch (IOException ioe) {
    } catch (SecurityException se) {
    }

    try {
        // attempt to load from a local file, used when running as
        // an application, or as a signed applet
        try { // first try to catch any security exceptions
            try {
                stream = new FileInputStream(dataPath(theFilename));
                if (stream != null)
                    return stream;
            } catch (IOException e2) {
            }

            try {
                stream = new FileInputStream(appPath(theFilename));
                if (stream != null)
                    return stream;
            } catch (Exception e) {
            } // ignored

            try {
                stream = new FileInputStream(theFilename);
                if (stream != null)
                    return stream;
            } catch (IOException e1) {
            }

        } catch (SecurityException se) {
        } // online, whups

    } catch (Exception e) {
        //die(e.getMessage(), e);
        e.printStackTrace();
    }
    return null;
}

From source file:org.dbmaintain.script.repository.impl.ArchiveScriptLocation.java

/**
 * @param scriptLocation The location of the jar file, not null
 * @return The properties as a properties map
 *//* w  w w  . j  a  v a2s  .c  o  m*/
@Override
protected Properties getCustomProperties(File scriptLocation) {
    InputStream configurationInputStream = null;
    try {
        JarFile jarFile = createJarFile(scriptLocation);
        ZipEntry configurationEntry = jarFile.getEntry(LOCATION_PROPERTIES_FILENAME);
        if (configurationEntry == null) {
            // no custom config found in meta-inf folder, skipping
            return null;
        }
        Properties configuration = new Properties();
        configurationInputStream = jarFile.getInputStream(configurationEntry);
        configuration.load(configurationInputStream);
        return configuration;
    } catch (IOException e) {
        throw new DbMaintainException("Error while reading configuration file " + LOCATION_PROPERTIES_FILENAME
                + " from jar file " + scriptLocation, e);
    } finally {
        closeQuietly(configurationInputStream);
    }
}

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

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

    //Init url/*from   www.ja  va  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.migratebird.script.repository.impl.ArchiveScriptLocation.java

/**
 * @param scriptLocation The location of the jar file, not null
 * @return The properties as a properties map
 *//*from   w  w w  .j  a v a  2 s  . c o m*/
@Override
protected Properties getCustomProperties(File scriptLocation) {
    InputStream configurationInputStream = null;
    try {
        JarFile jarFile = createJarFile(scriptLocation);
        ZipEntry configurationEntry = jarFile.getEntry(LOCATION_PROPERTIES_FILENAME);
        if (configurationEntry == null) {
            // no custom config found in meta-inf folder, skipping
            return null;
        }
        Properties configuration = new Properties();
        configurationInputStream = jarFile.getInputStream(configurationEntry);
        configuration.load(configurationInputStream);
        return configuration;
    } catch (IOException e) {
        throw new MigrateBirdException("Error while reading configuration file " + LOCATION_PROPERTIES_FILENAME
                + " from jar file " + scriptLocation, e);
    } finally {
        closeQuietly(configurationInputStream);
    }
}

From source file:com.wavemaker.commons.classloader.ThrowawayFileClassLoader.java

@Override
protected URL findResource(String name) {

    URL ret = null;/*from   www .  java2s  . c  om*/
    JarFile jarFile = null;

    try {
        for (Resource entry : this.classPath) {
            if (entry.getFilename().toLowerCase().endsWith(".jar")) {
                jarFile = new JarFile(entry.getFile());
                ZipEntry ze = jarFile.getEntry(name);
                jarFile.close();

                if (ze != null) {
                    ret = new URL("jar:" + entry.getURL() + "!/" + name);
                    break;
                }
            } else {
                Resource file = entry.createRelative(name);
                if (file.exists()) {
                    ret = file.getURL();
                    break;
                }
            }
        }
    } catch (IOException e) {
        throw new WMRuntimeException(e);
    }

    return ret;
}