Example usage for java.net JarURLConnection getJarFile

List of usage examples for java.net JarURLConnection getJarFile

Introduction

In this page you can find the example usage for java.net JarURLConnection getJarFile.

Prototype

public abstract JarFile getJarFile() throws IOException;

Source Link

Document

Return the JAR file for this connection.

Usage

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.data.SessionBean.java

/** Return a List with all the available bankruptcy functions by using dynamic class loading */
public List getAvailableBankruptcyFunctions() {
    try {//from w  w  w  .  j  ava  2 s.  c  o m
        List bankruptcyFunctions = new ArrayList();
        String pckgname = "edu.caltechUcla.sselCassel.projects.jMarkets.shared.functions";
        String name = "/edu/caltechUcla/sselCassel/projects/jMarkets/shared/functions";

        // Get a File object for the package
        URL url = SessionBean.class.getResource(name);
        URI uri = new URI(url.getPath());

        URL ori_url = new URL(url.getProtocol() + ":" + uri.getPath());

        File directory = new File(ori_url.getFile());

        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (int i = 0; i < files.length; i++) {
                // we are only interested in .class files
                if (files[i].endsWith(".class")) {
                    // removes the .class extension
                    String classname = files[i].substring(0, files[i].length() - 6);

                    try {
                        // Try to create an instance of the object
                        Object o = Class.forName(pckgname + "." + classname).newInstance();

                        if (o instanceof BankruptcyFunction && classname.endsWith("Function")) {
                            BankruptcyBean bankruptcyBean = new BankruptcyBean();
                            String bankruptcyName = classname.substring(0, classname.length() - 8);
                            bankruptcyBean.setName(bankruptcyName);

                            bankruptcyFunctions.add(bankruptcyBean);
                        }
                    } catch (ClassNotFoundException e) {
                        log.warn("Error loading bankruptcy function class", e);
                    } catch (InstantiationException e) {
                        //log.warn("Loaded verifier class does not have a default constructor!" + MSConstants.newline + e);
                    } catch (IllegalAccessException e) {
                        log.warn("Loaded bankruptcy function class is not public!", e);
                    }
                }
            }
        }

        //check the jar file if the verifiers are not in the file system
        else {
            try {
                JarURLConnection conn = (JarURLConnection) url.openConnection();
                String starts = conn.getEntryName();
                JarFile jfile = conn.getJarFile();
                Enumeration e = jfile.entries();
                while (e.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry) e.nextElement();
                    String entryname = entry.getName();
                    if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length())
                            && entryname.endsWith(".class")) {
                        String classname = entryname.substring(0, entryname.length() - 6);
                        if (classname.startsWith("/"))
                            classname = classname.substring(1);
                        classname = classname.replace('/', '.');
                        try {
                            // Try to create an instance of the object
                            Object o = Class.forName(classname).newInstance();

                            if (o instanceof BankruptcyFunction && classname.endsWith("Function")) {
                                String cname = classname.substring(classname.lastIndexOf('.') + 1);

                                BankruptcyBean bankruptcyBean = new BankruptcyBean();
                                String bankruptcyName = cname.substring(0, cname.length() - 8);
                                bankruptcyBean.setName(bankruptcyName);

                                bankruptcyFunctions.add(bankruptcyBean);
                            }
                        } catch (ClassNotFoundException cnfex) {
                            log.warn("Error loading bankruptcy function class", cnfex);
                        } catch (InstantiationException iex) {
                            // We try to instanciate an interface
                            // or an object that does not have a
                            // default constructor
                        } catch (IllegalAccessException iaex) {
                            log.warn("Loaded bankruptcy function class is not public!", iaex);
                        }
                    }
                }
            } catch (IOException e) {
                log.warn("Unknown IO Error", e);
            }
        }

        return bankruptcyFunctions;
    } catch (Exception e) {
        log.error("Failed to return a list of bankruptcy functions", e);
    }
    return null;
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.data.SessionBean.java

/** Return a List with all the available payoff functions by using dynamic class loading */
public List getAvailablePayoffFunctions() {
    try {//  w  ww  .j  a  v a2 s  .com
        List payoffFunctions = new ArrayList();
        String pckgname = "edu.caltechUcla.sselCassel.projects.jMarkets.shared.functions";
        String name = "/edu/caltechUcla/sselCassel/projects/jMarkets/shared/functions";

        // Get a File object for the package
        URL url = SessionBean.class.getResource(name);

        URI uri = new URI(url.getPath());

        URL ori_url = new URL(url.getProtocol() + ":" + uri.getPath());

        File directory = new File(ori_url.getFile());

        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (int i = 0; i < files.length; i++) {
                // we are only interested in .class files
                if (files[i].endsWith(".class")) {
                    // removes the .class extension
                    String classname = files[i].substring(0, files[i].length() - 6);

                    try {
                        // Try to create an instance of the object
                        Object o = Class.forName(pckgname + "." + classname).newInstance();

                        if (o instanceof PayoffFunction && classname.endsWith("Function")) {
                            PayoffBean payoffBean = new PayoffBean();
                            String payoffName = classname.substring(0, classname.length() - 8);
                            payoffBean.setName(payoffName);

                            payoffFunctions.add(payoffBean);
                        }
                    } catch (ClassNotFoundException e) {
                        log.warn("Error loading payoff function class", e);
                    } catch (InstantiationException e) {
                        //log.warn("Loaded verifier class does not have a default constructor!" + MSConstants.newline + e);
                    } catch (IllegalAccessException e) {
                        log.warn("Loaded payoff function class is not public!", e);
                    }
                }
            }
        }

        //check the jar file if the verifiers are not in the file system
        else {
            try {
                JarURLConnection conn = (JarURLConnection) url.openConnection();
                String starts = conn.getEntryName();
                JarFile jfile = conn.getJarFile();
                Enumeration e = jfile.entries();
                while (e.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry) e.nextElement();
                    String entryname = entry.getName();
                    if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length())
                            && entryname.endsWith(".class")) {
                        String classname = entryname.substring(0, entryname.length() - 6);
                        if (classname.startsWith("/"))
                            classname = classname.substring(1);
                        classname = classname.replace('/', '.');
                        try {
                            // Try to create an instance of the object
                            Object o = Class.forName(classname).newInstance();

                            if (o instanceof PayoffFunction && classname.endsWith("Function")) {
                                String cname = classname.substring(classname.lastIndexOf('.') + 1);

                                PayoffBean payoffBean = new PayoffBean();
                                String payoffName = cname.substring(0, cname.length() - 8);
                                payoffBean.setName(payoffName);

                                payoffFunctions.add(payoffBean);
                            }
                        } catch (ClassNotFoundException cnfex) {
                            log.warn("Error loading payoff function class", cnfex);
                        } catch (InstantiationException iex) {
                            // We try to instanciate an interface
                            // or an object that does not have a
                            // default constructor
                        } catch (IllegalAccessException iaex) {
                            log.warn("Loaded payoff function class is not public!", iaex);
                        }
                    }
                }
            } catch (IOException e) {
                log.warn("Unknown IO Error", e);
            }
        }

        return payoffFunctions;
    } catch (Exception e) {
        log.error("Failed to return a list of payoff functions", e);
    }
    return null;
}

From source file:org.hyperic.hq.product.server.session.PluginManagerImpl.java

private File getFileAndValidateJar(String filename, byte[] bytes) throws PluginDeployException {
    ByteArrayInputStream bais = null;
    JarInputStream jis = null;/*from  ww w. j a  va 2  s .  c o  m*/
    FileOutputStream fos = null;
    String file = null;
    try {
        bais = new ByteArrayInputStream(bytes);
        jis = new JarInputStream(bais);
        final Manifest manifest = jis.getManifest();
        if (manifest == null) {
            throw new PluginDeployException("plugin.manager.jar.manifest.does.not.exist", filename);
        }
        file = TMP_DIR + File.separator + filename;
        fos = new FileOutputStream(file);
        fos.write(bytes);
        fos.flush();
        final File rtn = new File(file);
        final URL url = new URL("jar", "", "file:" + file + "!/");
        final JarURLConnection jarConn = (JarURLConnection) url.openConnection();
        final JarFile jarFile = jarConn.getJarFile();
        processJarEntries(jarFile, file, filename);
        return rtn;
    } catch (IOException e) {
        final File toRemove = new File(file);
        if (toRemove != null && toRemove.exists()) {
            toRemove.delete();
        }
        throw new PluginDeployException("plugin.manager.file.ioexception", e, filename);
    } finally {
        close(jis);
        close(fos);
    }
}

From source file:catalina.startup.ContextConfig.java

/**
 * Scan the JAR file at the specified resource path for TLDs in the
 * <code>META-INF</code> subdirectory, and scan them for application
 * event listeners that need to be registered.
 *
 * @param resourcePath Resource path of the JAR file to scan
 *
 * @exception Exception if an exception occurs while scanning this JAR
 *///from ww  w  .j  a v  a  2 s.  c  om
private void tldScanJar(String resourcePath) throws Exception {

    if (debug >= 1) {
        log(" Scanning JAR at resource path '" + resourcePath + "'");
    }

    JarFile jarFile = null;
    String name = null;
    InputStream inputStream = null;
    try {
        URL url = context.getServletContext().getResource(resourcePath);
        if (url == null) {
            throw new IllegalArgumentException(sm.getString("contextConfig.tldResourcePath", resourcePath));
        }
        url = new URL("jar:" + url.toString() + "!/");
        JarURLConnection conn = (JarURLConnection) url.openConnection();
        conn.setUseCaches(false);
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            name = entry.getName();
            if (!name.startsWith("META-INF/")) {
                continue;
            }
            if (!name.endsWith(".tld")) {
                continue;
            }
            if (debug >= 2) {
                log("  Processing TLD at '" + name + "'");
            }
            inputStream = jarFile.getInputStream(entry);
            tldScanStream(inputStream);
            inputStream.close();
            inputStream = null;
            name = null;
        }
        // FIXME - Closing the JAR file messes up the class loader???
        //            jarFile.close();
    } catch (Exception e) {
        if (name == null) {
            throw new ServletException(sm.getString("contextConfig.tldJarException", resourcePath), e);
        } else {
            throw new ServletException(sm.getString("contextConfig.tldEntryException", name, resourcePath), e);
        }
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Throwable t) {
                ;
            }
            inputStream = null;
        }
        if (jarFile != null) {
            // FIXME - Closing the JAR file messes up the class loader???
            //                try {
            //                    jarFile.close();
            //                } catch (Throwable t) {
            //                    ;
            //                }
            jarFile = null;
        }
    }

}

From source file:com.opensymphony.xwork2.util.finder.ResourceFinder.java

private URL findResource(String resourceName, URL... search) {
    for (int i = 0; i < search.length; i++) {
        URL currentUrl = search[i];
        if (currentUrl == null) {
            continue;
        }/*  w w  w . j av  a 2  s  .  com*/
        JarFile jarFile = null;
        try {
            String protocol = currentUrl.getProtocol();
            if ("jar".equals(protocol)) {
                /*
                * If the connection for currentUrl or resURL is
                * used, getJarFile() will throw an exception if the
                * entry doesn't exist.
                */
                URL jarURL = ((JarURLConnection) currentUrl.openConnection()).getJarFileURL();
                try {
                    JarURLConnection juc = (JarURLConnection) new URL("jar", "", jarURL.toExternalForm() + "!/")
                            .openConnection();
                    jarFile = juc.getJarFile();
                } catch (IOException e) {
                    // Don't look for this jar file again
                    search[i] = null;
                    throw e;
                }

                String entryName;
                if (currentUrl.getFile().endsWith("!/")) {
                    entryName = resourceName;
                } else {
                    String file = currentUrl.getFile();
                    int sepIdx = file.lastIndexOf("!/");
                    if (sepIdx == -1) {
                        // Invalid URL, don't look here again
                        search[i] = null;
                        continue;
                    }
                    sepIdx += 2;
                    StringBuilder sb = new StringBuilder(file.length() - sepIdx + resourceName.length());
                    sb.append(file.substring(sepIdx));
                    sb.append(resourceName);
                    entryName = sb.toString();
                }
                if ("META-INF/".equals(entryName) && jarFile.getEntry("META-INF/MANIFEST.MF") != null) {
                    return targetURL(currentUrl, "META-INF/MANIFEST.MF");
                }
                if (jarFile.getEntry(entryName) != null) {
                    return targetURL(currentUrl, resourceName);
                }
            } else if ("file".equals(protocol)) {
                String baseFile = currentUrl.getFile();
                String host = currentUrl.getHost();
                int hostLength = 0;
                if (host != null) {
                    hostLength = host.length();
                }
                StringBuilder buf = new StringBuilder(
                        2 + hostLength + baseFile.length() + resourceName.length());

                if (hostLength > 0) {
                    buf.append("//").append(host);
                }
                // baseFile always ends with '/'
                buf.append(baseFile);
                String fixedResName = resourceName;
                // Do not create a UNC path, i.e. \\host
                while (fixedResName.startsWith("/") || fixedResName.startsWith("\\")) {
                    fixedResName = fixedResName.substring(1);
                }
                buf.append(fixedResName);
                String filename = buf.toString();
                File file = new File(filename);
                File file2 = new File(URLDecoder.decode(filename));

                if (file.exists() || file2.exists()) {
                    return targetURL(currentUrl, fixedResName);
                }
            } else {
                URL resourceURL = targetURL(currentUrl, resourceName);
                URLConnection urlConnection = resourceURL.openConnection();

                try {
                    urlConnection.getInputStream().close();
                } catch (SecurityException e) {
                    return null;
                }
                // HTTP can return a stream on a non-existent file
                // So check for the return code;
                if (!"http".equals(resourceURL.getProtocol())) {
                    return resourceURL;
                }

                int code = ((HttpURLConnection) urlConnection).getResponseCode();
                if (code >= 200 && code < 300) {
                    return resourceURL;
                }
            }
        } catch (MalformedURLException e) {
            // Keep iterating through the URL list
        } catch (IOException e) {
        } catch (SecurityException e) {
        }
    }
    return null;
}

From source file:org.teragrid.portal.filebrowser.applet.ConfigOperation.java

private void readVersionInformation() {
    InputStream stream = null;/* www.j a v  a2 s.  c  om*/
    try {
        JarFile tgfmJar = null;
        URL jarname = Class.forName("org.teragrid.portal.filebrowser.applet.ConfigOperation")
                .getResource("ConfigOperation.class");
        JarURLConnection c = (JarURLConnection) jarname.openConnection();
        tgfmJar = c.getJarFile();
        stream = tgfmJar.getInputStream(tgfmJar.getEntry("META-INF/MANIFEST.MF"));
        Manifest manifest = new Manifest(stream);
        Attributes attributes = manifest.getMainAttributes();
        for (Object attributeName : attributes.keySet()) {
            if (((Attributes.Name) attributeName).toString().equals(("Implementation-Version"))) {
                ConfigSettings.SOFTWARE_VERSION = attributes.getValue("Implementation-Version");
            } else if (((Attributes.Name) attributeName).toString().equals(("Built-Date"))) {
                ConfigSettings.SOFTWARE_BUILD_DATE = attributes.getValue("Built-Date");
            }

            LogManager
                    .debug(attributeName + ": " + attributes.getValue((Attributes.Name) attributeName) + "\n");
        }

        stream.close();
    } catch (Exception e) {
        LogManager.error("Failed to retreive version information.", e);
    } finally {
        try {
            stream.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.teragrid.portal.filebrowser.applet.ConfigOperation.java

/**
 * Deploy the bundled files and unpack several jars including help, 
 * and the TeraGrid trusted ca's./*w ww  .  jav  a 2 s  .  c o m*/
 */
private void setup() {

    appHome = getApplicationHome();

    try {
        JarFile tgfmJar = null;

        URL jarname = Class.forName("org.teragrid.portal.filebrowser.applet.ConfigOperation")
                .getResource("ConfigOperation.class");

        readVersionInformation();

        // delete the old certs directory
        FileUtils.deleteRecursive(getCertificateDir());

        for (String caURL : TRUSTED_CA_TARBALLS) {
            deployRemoteCATarball(caURL);
        }

        if (jarname.getProtocol().startsWith("jar") || jarname.getProtocol().startsWith("htt")) {

            JarURLConnection c = (JarURLConnection) jarname.openConnection();
            tgfmJar = c.getJarFile();
            AppMain.updateSplash(-1, "Unpacking help system...");
            try {
                FileUtils.unpackJarEntry(tgfmJar, BUNDLED_JAR_HELP, getHelpDir());
            } catch (Exception e) {
                LogManager.error("Failed to unpack help files.", e);
            }

            // unpack keystore
            try {
                JarEntry keystoreEntry = new JarEntry(tgfmJar.getEntry("security/keystore"));
                FileUtils.extractJarEntry(tgfmJar, keystoreEntry,
                        new File(getCertificateDir() + File.separator + "keystore"));
            } catch (Exception e) {
                LogManager.error("Failed to unpack keystore.", e);
            }

        } else {
            LogManager.debug("Not running from jar. Structure already in place.");

            // copy help
            AppMain.updateSplash(-1, "Unpacking help system...");
            File srcHelpDir = new File(appHome + "help");
            if (!srcHelpDir.exists()) {
                throw new IOException("Failed to copy help files from " + srcHelpDir.getAbsolutePath());
            }
            try {
                org.apache.commons.io.FileUtils.copyDirectory(srcHelpDir, new File(getHelpDir()));
            } catch (Exception e) {
                LogManager.error("Failed to copy help files.", e);
            }

            File srcKeystore = new File(appHome + "security" + File.separator + "keystore");
            if (!srcKeystore.exists()) {
                throw new IOException("Failed to copy keystore from " + srcKeystore.getAbsolutePath());
            }

            try {
                File destKeystore = new File(getCertificateDir() + File.separator + "keystore");
                org.apache.commons.io.FileUtils.copyFile(srcKeystore, destKeystore);
                System.out.println("length of copied keystore is " + destKeystore.length());
            } catch (Exception e) {
                LogManager.error("Failed to copy keystore.", e);
            }

        }

        configureCoGProperties();

    } catch (Exception e) {
        LogManager.error("Failed to set up user environment.", e);
    }
}

From source file:org.kchine.r.server.DirectJNI.java

public static void generateMaps(URL jarUrl, boolean rawClasses) {

    try {//www  .  jav a  2s  .c o m

        _mappingClassLoader = new URLClassLoader(new URL[] { jarUrl }, DirectJNI.class.getClassLoader());
        Vector<String> list = new Vector<String>();
        JarURLConnection jarConnection = (JarURLConnection) jarUrl.openConnection();
        JarFile jarfile = jarConnection.getJarFile();
        Enumeration<JarEntry> enu = jarfile.entries();
        while (enu.hasMoreElements()) {
            String entry = enu.nextElement().toString();
            if (entry.endsWith(".class"))
                list.add(entry.replace('/', '.').substring(0, entry.length() - ".class".length()));
        }

        log.info(list);

        for (int i = 0; i < list.size(); ++i) {
            String className = list.elementAt(i);
            if (className.startsWith("org.kchine.r.packages.")
                    && !className.startsWith("org.kchine.r.packages.rservices")) {
                Class<?> c_ = _mappingClassLoader.loadClass(className);

                if (c_.getSuperclass() != null && c_.getSuperclass().equals(RObject.class)
                        && !Modifier.isAbstract(c_.getModifiers())) {

                    if (c_.equals(RLogical.class) || c_.equals(RInteger.class) || c_.equals(RNumeric.class)
                            || c_.equals(RComplex.class) || c_.equals(RChar.class) || c_.equals(RMatrix.class)
                            || c_.equals(RArray.class) || c_.equals(RList.class) || c_.equals(RDataFrame.class)
                            || c_.equals(RFactor.class) || c_.equals(REnvironment.class)
                            || c_.equals(RVector.class) || c_.equals(RUnknown.class)) {
                    } else {
                        String rclass = DirectJNI.getRClassForBean(jarfile, className);
                        _s4BeansHash.put(className, c_);
                        _s4BeansMapping.put(rclass, className);
                        _s4BeansMappingRevert.put(className, rclass);
                    }

                } else if ((rawClasses && c_.getSuperclass() != null && c_.getSuperclass().equals(Object.class))
                        || (!rawClasses && RPackage.class.isAssignableFrom(c_) && (c_.isInterface()))) {

                    String shortClassName = className.substring(className.lastIndexOf('.') + 1);
                    _packageNames.add(shortClassName);

                    Vector<Class<?>> v = _rPackageInterfacesHash.get(className);
                    if (v == null) {
                        v = new Vector<Class<?>>();
                        _rPackageInterfacesHash.put(className, v);
                    }
                    v.add(c_);

                } else {
                    String nameWithoutPackage = className.substring(className.lastIndexOf('.') + 1);
                    if (nameWithoutPackage.indexOf("Factory") != -1
                            && c_.getMethod("setData", new Class[] { RObject.class }) != null) {
                        // if
                        // (DirectJNI._factoriesMapping.get(nameWithoutPackage
                        // )
                        // != null) throw new Exception("Factories Names
                        // Conflict : two " + nameWithoutPackage);
                        _factoriesMapping.put(nameWithoutPackage, className);
                        if (Modifier.isAbstract(c_.getModifiers()))
                            _abstractFactories.add(className);
                    }
                }
            }
        }

        // log.info("s4Beans:" +s4Beans);
        log.info("rPackageInterfaces:" + _packageNames);
        log.info("s4Beans MAP :" + _s4BeansMapping);
        log.info("s4Beans Revert MAP :" + _s4BeansMappingRevert);
        log.info("factories :" + _factoriesMapping);
        log.info("r package interface hash :" + _rPackageInterfacesHash);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}