Example usage for java.util.jar JarFile getJarEntry

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

Introduction

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

Prototype

public JarEntry getJarEntry(String name) 

Source Link

Document

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

Usage

From source file:org.rhq.plugins.jbossas.JBossASServerComponent.java

/**
 * Check to see if the passed file is actually in jar format and contains a
 * <ul>/*from  ww  w . jav a2s  . co  m*/
 * <li>WEB-INF/web.xml for .war </li>
 * <li>META-INF/application.xml for .ear</li>
 * <li>META-INF/jboss.service.xml for .sar</li>
 * </ul>
 * @param file File to check
 * @param type Type to match - see RESOURCE_TYPE_SAR, RESOURCE_TYPE_WAR and RESOURCE_TYPE_EAR
 * @return true is the file is in jar format and matches the type
 */
private boolean isOfType(File file, String type) {
    JarFile jfile = null;
    try {
        jfile = new JarFile(file);
        JarEntry entry;
        if (RESOURCE_TYPE_WAR.equals(type))
            entry = jfile.getJarEntry("WEB-INF/web.xml");
        else if (RESOURCE_TYPE_EAR.equals(type))
            entry = jfile.getJarEntry("META-INF/application.xml");
        else if (RESOURCE_TYPE_SAR.equals(type)) // Not yet used
            entry = jfile.getJarEntry("META-INF/jboss-service.xml");
        else {
            entry = null; // unknown type
            log.warn("isOfType: " + type + " is unknown - not a valid file");
        }

        if (entry != null)
            return true;

        return false;
    } catch (Exception e) {
        log.info(e.getMessage());
        return false;
    } finally {
        if (jfile != null)
            try {
                jfile.close();
            } catch (IOException e) {
                log.info("Exception when trying to close the war file: " + e.getMessage());
            }
    }
}

From source file:org.spout.api.plugin.CommonPlugin.java

@Override
public InputStream getResource(String path) {
    Validate.notNull(path);//from  w w w . j av  a2 s  .c o m
    JarFile jar;
    try {
        jar = new JarFile(getFile());
    } catch (IOException e) {
        return null;
    }
    JarEntry entry = jar.getJarEntry(path);
    try {
        return entry == null ? null : jar.getInputStream(entry);
    } catch (IOException e) {
        return null;
    }
}

From source file:org.spout.api.plugin.CommonPluginLoader.java

/**
 * @param file Plugin file object/*w  w  w  . ja va2  s .co  m*/
 * @return The current plugin's description element.
 *
 * @throws InvalidPluginException
 * @throws InvalidDescriptionFileException
 */
protected synchronized PluginDescriptionFile getDescription(File file)
        throws InvalidPluginException, InvalidDescriptionFileException {
    if (!file.exists()) {
        throw new InvalidPluginException(file.getName() + " does not exist!");
    }

    PluginDescriptionFile description = null;
    JarFile jar = null;
    InputStream in = null;
    try {
        // Spout plugin properties file
        jar = new JarFile(file);
        JarEntry entry = jar.getJarEntry(YAML_SPOUT);

        // Fallback plugin properties file
        if (entry == null) {
            entry = jar.getJarEntry(YAML_OTHER);
        }

        if (entry == null) {
            throw new InvalidPluginException("Jar has no properties.yml or plugin.yml!");
        }

        in = jar.getInputStream(entry);
        description = new PluginDescriptionFile(in);
    } catch (IOException e) {
        throw new InvalidPluginException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                engine.getLogger().log(Level.WARNING, "Problem closing input stream", e);
            }
        }
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
                engine.getLogger().log(Level.WARNING, "Problem closing jar input stream", e);
            }
        }
    }
    return description;
}

From source file:org.spout.api.plugin.PluginLoader.java

/**
 * @param file Plugin file object/* w w w  .j a  v a  2s .  c o  m*/
 * @return The current plugin's description element.
 */
protected static synchronized PluginDescriptionFile getDescription(File file)
        throws InvalidPluginException, InvalidDescriptionFileException {
    if (!file.exists()) {
        throw new InvalidPluginException(file.getName() + " does not exist!");
    }

    PluginDescriptionFile description = null;
    JarFile jar = null;
    InputStream in = null;
    try {
        // Spout plugin properties file
        jar = new JarFile(file);
        JarEntry entry = jar.getJarEntry(YAML_SPOUT);

        // Fallback plugin properties file
        if (entry == null) {
            entry = jar.getJarEntry(YAML_OTHER);
        }

        if (entry == null) {
            throw new InvalidPluginException("Jar has no properties.yml or plugin.yml!");
        }

        in = jar.getInputStream(entry);
        description = new PluginDescriptionFile(in);
    } catch (IOException e) {
        throw new InvalidPluginException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                Spout.getLogger().log(Level.WARNING, "Problem closing input stream", e);
            }
        }
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
                Spout.getLogger().log(Level.WARNING, "Problem closing jar input stream", e);
            }
        }
    }
    return description;
}

From source file:org.spout.engine.filesystem.CommonFileSystem.java

private void allowInstallation(final CommandSource source, final String plugin) {
    Spout.getScheduler().scheduleAsyncTask(Spout.getEngine(), new Runnable() {
        @Override//from  ww w  .ja v a  2s  .  c  o m
        public void run() {
            synchronized (requestedInstallations) {

                JarFile jar = null;
                InputStream in = null;

                try {
                    // obtain plugin stream
                    URI uri = requestedInstallations.get(plugin);
                    in = new BufferedInputStream(uri.toURL().openStream());
                    String path = uri.toString();
                    File file = new File(UPDATES_DIRECTORY, path.substring(path.lastIndexOf('/') + 1));

                    // copy to updates
                    source.sendMessage("Downloading " + plugin + " to the updates folder...");
                    FileUtils.copyInputStreamToFile(in, file);
                    source.sendMessage("Done.");

                    // check the validity of plugin
                    jar = new JarFile(file);
                    if (jar.getJarEntry("properties.yml") == null && jar.getJarEntry("plugin.yml") == null) {
                        source.sendMessage(
                                "The downloaded file has no valid plugin description file, marking file to be deleted.");
                        if (!file.delete()) {
                            file.deleteOnExit();
                        }
                        return;
                    }

                    source.sendMessage(plugin
                            + " has been successfully downloaded to the updates folder, it will be installed on next run.");
                } catch (MalformedURLException e) {
                    throw new SpoutRuntimeException("The plugin's URL is invalid", e);
                } catch (IOException e) {
                    throw new SpoutRuntimeException("Error downloading the plugin", e);
                } finally {
                    // close the jar
                    try {
                        if (jar != null) {
                            jar.close();
                        }
                    } catch (IOException e) {
                        Spout.getLogger().log(Level.WARNING, "Error closing JAR file", e);
                    }

                    // close the input stream
                    try {
                        if (in != null) {
                            in.close();
                        }
                    } catch (IOException e) {
                        Spout.getLogger().log(Level.WARNING, "Error closing plugin stream", e);
                    }
                }
                requestedInstallations.remove(plugin);
            }
        }
    });
}

From source file:org.spoutcraft.launcher.launch.MinecraftClassLoader.java

private Class<?> findClassInjar(String name, File file) throws ClassNotFoundException {
    byte classByte[];
    Class<?> result = null;
    JarFile jar = null;
    try {//from   w  w  w.  j  a  v  a 2 s  .c  om
        jar = new JarFile(file);
        JarEntry entry = jar.getJarEntry(name.replace(".", "/") + ".class");
        if (entry != null) {
            InputStream is = jar.getInputStream(entry);
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            int next = is.read();
            while (-1 != next) {
                byteStream.write(next);
                next = is.read();
            }

            classByte = byteStream.toByteArray();
            result = defineClass(name, classByte, 0, classByte.length,
                    new CodeSource(file.toURI().toURL(), (CodeSigner[]) null));
            loadedClasses.put(name, result);
            return result;
        }
    } catch (FileNotFoundException e) {
        // Assume temp file has been cleaned if the thread is interrupted
        if (!Thread.currentThread().isInterrupted()) {
            e.printStackTrace();
        }
    } catch (ZipException zipEx) {
        System.out.println("Failed to open " + name + " from " + file.getPath());
        zipEx.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            jar.close();
        } catch (IOException ignore) {
        }
    }
    return null;
}

From source file:org.springfield.lou.application.ApplicationManager.java

private void processUploadedWar(File warfile, String wantedname) {
    // lets first check some vitals to check what it is
    String warfilename = warfile.getName();
    if (warfilename.startsWith("smt_") && warfilename.endsWith("app.war")) {
        // ok so filename checks out is smt_[name]app.war format
        String appname = warfilename.substring(4, warfilename.length() - 7);
        if (wantedname.equals(appname)) {
            // ok found file is the wanted file
            // format "29-Aug-2013-16:55"
            System.out.println("NEW VERSION OF " + appname + " FOUND INSTALLING");
            Date now = new Date();
            SimpleDateFormat df = new SimpleDateFormat("d-MMM-yyyy-HH:mm");
            String datestring = df.format(now);
            String writedir = "/springfield/lou/apps/" + appname + "/" + datestring;

            // create the node
            Html5AvailableApplication vapp = getAvailableApplication(appname);
            String newbody = "<fsxml><properties></properties></fsxml>";

            ServiceInterface smithers = ServiceManager.getService("smithers");
            if (smithers == null)
                return;
            FsNode tnode = Fs.getNode("/domain/internal/service/lou/apps/" + appname);
            if (tnode == null) {
                smithers.put("/domain/internal/service/lou/apps/" + appname + "/properties", newbody,
                        "text/xml");
            }//  ww w  . jav a  2s .  c  o m
            smithers.put(
                    "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring + "/properties",
                    newbody, "text/xml");

            // make all the dirs we need
            File md = new File(writedir);
            md.mkdirs();
            md = new File(writedir + "/war");
            md.mkdirs();
            md = new File(writedir + "/jar");
            md.mkdirs();
            md = new File(writedir + "/components");
            md.mkdirs();
            md = new File(writedir + "/css");
            md.mkdirs();
            md = new File(writedir + "/libs");
            md.mkdirs();

            try {
                JarFile war = new JarFile(warfile);

                // ok lets first find the jar file !
                JarEntry entry = war.getJarEntry("WEB-INF/lib/smt_" + appname + "app.jar");
                if (entry != null) {
                    byte[] bytes = readJarEntryToBytes(war.getInputStream(entry));
                    writeBytesToFile(bytes, writedir + "/jar/smt_" + appname + "app.jar");
                }
                // unpack all in eddie dir
                Enumeration<JarEntry> iter = war.entries();
                while (iter.hasMoreElements()) {
                    JarEntry lentry = iter.nextElement();
                    //System.out.println("LI="+lentry.getName());
                    String lname = lentry.getName();
                    if (!lname.endsWith("/")) {
                        int pos = lname.indexOf("/" + appname + "/");
                        if (pos != -1) {
                            String nname = lname.substring(pos + appname.length() + 2);
                            String dname = nname.substring(0, nname.lastIndexOf('/'));
                            File de = new File(writedir + "/" + dname);
                            de.mkdirs();
                            byte[] bytes = readJarEntryToBytes(war.getInputStream(lentry));
                            writeBytesToFile(bytes, writedir + "/" + nname);
                        }
                    }
                }
                war.close();
                File ren = new File("/springfield/lou/uploaddir/" + warfilename);
                File nen = new File(writedir + "/war/smt_" + appname + "app.war");
                //System.out.println("REN="+warfilename);
                //System.out.println("REN="+writedir+"/war/smt_"+appname+"app.war");
                ren.renameTo(nen);

                loadAvailableApps();
                // should we make in development or production based on autodeploy ?
                vapp = getAvailableApplication(appname);
                if (vapp != null) {
                    String mode = vapp.getAutoDeploy();
                    if (appname.equals("dashboard")) {
                        mode = "development/production";
                    }
                    System.out.println("APPNAME=" + appname + " mode=" + mode);
                    if (mode.equals("production")) {
                        makeProduction(appname, datestring);
                    } else if (mode.equals("development")) {
                        makeDevelopment(appname, datestring);
                    } else if (mode.equals("development/production")) {
                        makeDevelopment(appname, datestring);
                        makeProduction(appname, datestring);
                    }
                }

                /*
                Html5ApplicationInterface app = getApplication("/domain/webtv/html5application/dashboard");
                if (app!=null) {
                 DashboardApplication dapp = (DashboardApplication)app;
                 dapp.newApplicationFound(appname);
                }
                */

                // lets tell set the available variable to tell the others we have it.
                FsNode unode = Fs
                        .getNode("/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring);
                if (unode != null) {
                    String warlist = unode.getProperty("waravailableat");
                    if (warlist == null || warlist.equals("")) {
                        Fs.setProperty(
                                "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring,
                                "waravailableat", LazyHomer.myip);
                    } else {
                        System.out.println("BUG ? Already available war " + warlist + " a=" + appname);
                    }
                }
            } catch (Exception e) {
                System.out.println("VERSION NOT READY STILL UPLOADING? RETRY WILL HAPPEN SOON");
            }
        }
    }
}

From source file:org.springfield.lou.application.ApplicationManager.java

private void processRemoteWar(File warfile, String wantedname, String datestring) {
    // lets first check some vitals to check what it is
    String warfilename = warfile.getName();
    if (warfilename.startsWith("smt_") && warfilename.endsWith("app.war")) {
        // ok so filename checks out is smt_[name]app.war format
        String appname = warfilename.substring(4, warfilename.length() - 7);
        if (wantedname.equals(appname)) {
            // ok found file is the wanted file
            // format "29-Aug-2013-16:55"
            System.out.println("NEW VERSION OF " + appname + " FOUND INSTALLING");

            String writedir = "/springfield/lou/apps/" + appname + "/" + datestring;

            // make all the dirs we need
            File md = new File(writedir);
            md.mkdirs();/*from w  w  w.j a  va 2  s  .c o m*/
            md = new File(writedir + "/war");
            md.mkdirs();
            md = new File(writedir + "/jar");
            md.mkdirs();
            md = new File(writedir + "/components");
            md.mkdirs();
            md = new File(writedir + "/css");
            md.mkdirs();
            md = new File(writedir + "/libs");
            md.mkdirs();

            try {
                JarFile war = new JarFile(warfile);

                // ok lets first find the jar file !
                JarEntry entry = war.getJarEntry("WEB-INF/lib/smt_" + appname + "app.jar");
                if (entry != null) {
                    byte[] bytes = readJarEntryToBytes(war.getInputStream(entry));
                    writeBytesToFile(bytes, writedir + "/jar/smt_" + appname + "app.jar");
                }
                // unpack all in eddie dir
                Enumeration<JarEntry> iter = war.entries();
                while (iter.hasMoreElements()) {
                    JarEntry lentry = iter.nextElement();
                    //System.out.println("LI="+lentry.getName());
                    String lname = lentry.getName();
                    if (!lname.endsWith("/")) {
                        int pos = lname.indexOf("/" + appname + "/");
                        if (pos != -1) {
                            String nname = lname.substring(pos + appname.length() + 2);
                            String dname = nname.substring(0, nname.lastIndexOf('/'));
                            File de = new File(writedir + "/" + dname);
                            de.mkdirs();
                            byte[] bytes = readJarEntryToBytes(war.getInputStream(lentry));
                            writeBytesToFile(bytes, writedir + "/" + nname);
                        }
                    }
                }
                war.close();
                File ren = new File("/springfield/lou/uploaddir/" + warfilename);
                File nen = new File(writedir + "/war/smt_" + appname + "app.war");
                ren.renameTo(nen);

                // lets tell set the available variable to tell the others we have it.

                FsNode unode = Fs
                        .getNode("/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring);
                if (unode != null) {
                    String warlist = unode.getProperty("waravailableat");
                    if (warlist == null || warlist.equals("")) {
                        Fs.setProperty(
                                "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring,
                                "waravailableat", LazyHomer.myip);
                    } else {
                        Fs.setProperty(
                                "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring,
                                "waravailableat", warlist + "," + LazyHomer.myip);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.tobarsegais.webapp.ContentServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = req.getPathInfo();
    if (path == null) {
        path = req.getServletPath();/*from ww w.  j av a 2 s  .com*/
    }
    int index = path.indexOf(PLUGINS_ROOT);
    if (index != -1) {
        path = path.substring(index + PLUGINS_ROOT.length() - 1);
    }
    Map<String, String> bundles = (Map<String, String>) getServletContext().getAttribute("bundles");
    for (index = path.indexOf('/'); index != -1; index = path.indexOf('/', index + 1)) {
        String key = path.substring(0, index);
        if (key.startsWith("/")) {
            key = key.substring(1);
        }
        if (bundles.containsKey(key)) {
            key = bundles.get(key);
        }
        URL resource = getServletContext()
                .getResource(ServletContextListenerImpl.BUNDLE_PATH + "/" + key + ".jar");
        if (resource == null) {
            continue;
        }
        URL jarResource = new URL("jar:" + resource + "!/");
        URLConnection connection = jarResource.openConnection();
        if (!(connection instanceof JarURLConnection)) {
            continue;
        }
        JarURLConnection jarConnection = (JarURLConnection) connection;
        JarFile jarFile = jarConnection.getJarFile();
        try {
            int endOfFileName = path.indexOf('#', index);
            endOfFileName = endOfFileName == -1 ? path.length() : endOfFileName;
            String fileName = path.substring(index + 1, endOfFileName);
            JarEntry jarEntry = jarFile.getJarEntry(fileName);
            if (jarEntry == null) {
                continue;
            }
            long size = jarEntry.getSize();
            if (size > 0 && size < Integer.MAX_VALUE) {
                resp.setContentLength((int) size);
            }
            resp.setContentType(getServletContext().getMimeType(fileName));
            InputStream in = null;
            OutputStream out = resp.getOutputStream();
            try {
                in = jarFile.getInputStream(jarEntry);
                IOUtils.copy(in, out);
            } finally {
                IOUtils.closeQuietly(in);
                out.close();
            }
            return;
        } finally {
            //jarFile.close();
        }
    }
    resp.sendError(404);
}

From source file:org.tobarsegais.webapp.ContentServlet.java

@Override
protected long getLastModified(HttpServletRequest req) {
    String path = req.getPathInfo();
    if (path == null) {
        path = req.getServletPath();/*from  www  . j av  a 2s. c o  m*/
    }
    int index = path.indexOf(PLUGINS_ROOT);
    if (index != -1) {
        path = path.substring(index + PLUGINS_ROOT.length() - 1);
    }
    Map<String, String> bundles = (Map<String, String>) getServletContext().getAttribute("bundles");
    try {
        for (index = path.indexOf('/'); index != -1; index = path.indexOf('/', index + 1)) {
            String key = path.substring(0, index);
            if (key.startsWith("/")) {
                key = key.substring(1);
            }
            if (bundles.containsKey(key)) {
                key = bundles.get(key);
            }
            URL resource = getServletContext()
                    .getResource(ServletContextListenerImpl.BUNDLE_PATH + "/" + key + ".jar");
            if (resource == null) {
                continue;
            }
            URL jarResource = new URL("jar:" + resource + "!/");
            URLConnection connection = jarResource.openConnection();
            if (!(connection instanceof JarURLConnection)) {
                continue;
            }
            JarURLConnection jarConnection = (JarURLConnection) connection;
            JarFile jarFile = jarConnection.getJarFile();
            try {
                int endOfFileName = path.indexOf('#', index);
                endOfFileName = endOfFileName == -1 ? path.length() : endOfFileName;
                String fileName = path.substring(index + 1, endOfFileName);
                JarEntry jarEntry = jarFile.getJarEntry(fileName);
                if (jarEntry == null) {
                    continue;
                }
                return jarEntry.getTime();
            } finally {
                //jarFile.close();
            }
        }
    } catch (IOException e) {
        // ignore
    }
    return -1;
}