Example usage for java.util.jar JarFile getInputStream

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

Introduction

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

Prototype

public synchronized InputStream getInputStream(ZipEntry ze) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:org.kepler.objectmanager.ActorMetadata.java

/**
 * try to locate and parse a moml file as a class
 *//*from w  ww.  jav a  2  s  .c om*/
protected ComponentEntity parseMoMLFile(String className) throws Exception {
    if (isDebugging)
        log.debug("parseMoMLFile(" + className + ")");

    JarFile jarFile = null;
    InputStream xmlStream = null;
    try {
        // first we need to find the file and read it
        File classFile = searchClasspath(className);
        StringWriter sw = new StringWriter();
        if (classFile.getName().endsWith(".jar")) {
            jarFile = new JarFile(classFile);
            ZipEntry entry = jarFile.getEntry(className.replace('.', '/') + ".xml");
            xmlStream = jarFile.getInputStream(entry);
        } else {
            xmlStream = new FileInputStream(classFile);
        }

        byte[] b = new byte[1024];
        int numread = xmlStream.read(b, 0, 1024);
        while (numread != -1) {
            String s = new String(b, 0, numread);
            sw.write(s);
            numread = xmlStream.read(b, 0, 1024);
        }
        sw.flush();
        // get the moml document
        String xmlDoc = sw.toString();
        sw.close();

        if (isDebugging)
            log.debug("**** MoMLParser ****");

        // use the moml parser to parse the doc
        MoMLParser parser = new MoMLParser();
        parser.reset();

        // System.out.println("processing " + className);
        NamedObj obj = parser.parse(xmlDoc);
        return (ComponentEntity) obj;
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
        if (xmlStream != null) {
            xmlStream.close();
        }
    }
}

From source file:JNLPAppletLauncher.java

/**
 * Check the native certificates with the ones in the jar file containing the
 * certificates for the JNLPAppletLauncher class (all must match).
 *//*from w ww .j a va2s  .c  o  m*/
private boolean checkNativeCertificates(JarFile jar, JarEntry entry, byte[] buf) throws IOException {

    // API states that we must read all of the data from the entry's
    // InputStream in order to be able to get its certificates

    InputStream is = jar.getInputStream(entry);
    int totalLength = (int) entry.getSize();
    int len;
    while ((len = is.read(buf)) > 0) {
    }
    is.close();

    // locate JNLPAppletLauncher certificates
    Certificate[] appletLauncherCerts = JNLPAppletLauncher.class.getProtectionDomain().getCodeSource()
            .getCertificates();
    if (appletLauncherCerts == null || appletLauncherCerts.length == 0) {
        throw new IOException("Cannot find certificates for JNLPAppletLauncher class");
    }

    // Get the certificates for the JAR entry
    Certificate[] nativeCerts = entry.getCertificates();
    if (nativeCerts == null || nativeCerts.length == 0) {
        return false;
    }

    int checked = 0;
    for (int i = 0; i < appletLauncherCerts.length; i++) {
        for (int j = 0; j < nativeCerts.length; j++) {
            if (nativeCerts[j].equals(appletLauncherCerts[i])) {
                checked++;
                break;
            }
        }
    }
    return (checked == appletLauncherCerts.length);
}

From source file:org.netbeans.nbbuild.MakeJnlp2.java

private void generateFiles() throws IOException, BuildException {

    final Set<String> declaredLocales = new HashSet<String>();

    final boolean useAllLocales;

    if ("*".equals(includelocales)) {
        useAllLocales = true;/*from   w w  w .  jav  a  2  s  . co  m*/
    } else if ("".equals(includelocales)) {
        useAllLocales = false;
    } else {
        useAllLocales = false;
        StringTokenizer tokenizer = new StringTokenizer(includelocales, ",");
        while (tokenizer.hasMoreElements()) {
            declaredLocales.add(tokenizer.nextToken());
        }
    }

    final Set<String> indirectFilePaths = new HashSet<String>();
    for (FileSet fs : new FileSet[] { indirectJars, indirectFiles }) {
        if (fs != null) {
            DirectoryScanner scan = fs.getDirectoryScanner(getProject());
            for (String f : scan.getIncludedFiles()) {
                indirectFilePaths.add(f.replace(File.pathSeparatorChar, '/'));
            }
        }
    }

    final ExecutorService executorService = Executors.newFixedThreadPool(nbThreads);

    final List<BuildException> exceptions = new ArrayList<BuildException>();

    for (final Iterator fileIt = files.iterator(); fileIt.hasNext();) {
        if (!exceptions.isEmpty()) {
            break;
        }

        final FileResource fr = (FileResource) fileIt.next();
        final File jar = fr.getFile();

        if (!jar.canRead()) {
            throw new BuildException("Cannot read file: " + jar);
        }

        //
        if (optimize && checkDuplicate(jar).isPresent()) {
            continue;
        }
        //

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                JarFile theJar = null;
                try {
                    theJar = new JarFile(jar);

                    String codenamebase = JarWithModuleAttributes
                            .extractCodeName(theJar.getManifest().getMainAttributes());
                    if (codenamebase == null) {
                        throw new BuildException("Not a NetBeans Module: " + jar);
                    }
                    {
                        int slash = codenamebase.indexOf('/');
                        if (slash >= 0) {
                            codenamebase = codenamebase.substring(0, slash);
                        }
                    }
                    String dashcnb = codenamebase.replace('.', '-');

                    String title;
                    String oneline;
                    String shrt;
                    String osDep = null;

                    {
                        String bundle = theJar.getManifest().getMainAttributes()
                                .getValue("OpenIDE-Module-Localizing-Bundle");
                        Properties prop = new Properties();
                        if (bundle != null) {
                            ZipEntry en = theJar.getEntry(bundle);
                            if (en == null) {
                                throw new BuildException("Cannot find entry: " + bundle + " in file: " + jar);
                            }
                            InputStream is = theJar.getInputStream(en);
                            prop.load(is);
                            is.close();
                        }
                        title = prop.getProperty("OpenIDE-Module-Name", codenamebase);
                        oneline = prop.getProperty("OpenIDE-Module-Short-Description", title);
                        shrt = prop.getProperty("OpenIDE-Module-Long-Description", oneline);
                    }

                    {
                        String osMan = theJar.getManifest().getMainAttributes()
                                .getValue("OpenIDE-Module-Requires");
                        if (osMan != null) {
                            if (osMan.indexOf("org.openide.modules.os.MacOSX") >= 0) { // NOI18N
                                osDep = "Mac OS X"; // NOI18N
                            } else if (osMan.indexOf("org.openide.modules.os.Linux") >= 0) { // NOI18N
                                osDep = "Linux"; // NOI18N
                            } else if (osMan.indexOf("org.openide.modules.os.Solaris") >= 0) { // NOI18N
                                osDep = "Solaris"; // NOI18N
                            } else if (osMan.indexOf("org.openide.modules.os.Windows") >= 0) { // NOI18N
                                osDep = "Windows"; // NOI18N
                            }
                        }
                    }

                    Map<String, List<File>> localizedFiles = verifyExtensions(jar, theJar.getManifest(),
                            dashcnb, codenamebase, verify, indirectFilePaths);

                    executedLocales = localizedFiles.keySet();

                    new File(targetFile, dashcnb).mkdir();

                    File signed = new File(new File(targetFile, dashcnb), jar.getName());

                    // +p
                    final JarConfigResolved jarConfig = signOrCopy(jar, signed);

                    File jnlp = new File(targetFile, dashcnb + ".jnlp");
                    StringWriter writeJNLP = new StringWriter();
                    writeJNLP.write("<?xml version='1.0' encoding='UTF-8'?>\n");
                    writeJNLP.write(
                            "<!DOCTYPE jnlp PUBLIC \"-//Sun Microsystems, Inc//DTD JNLP Descriptor 6.0//EN\" \"http://java.sun.com/dtd/JNLP-6.0.dtd\">\n");
                    writeJNLP.write("<jnlp spec='1.0+' codebase='" + codebase + "'>\n");
                    writeJNLP.write("  <information>\n");
                    writeJNLP.write("   <title>" + XMLUtil.toElementContent(title) + "</title>\n");
                    writeJNLP.write("   <vendor>NetBeans</vendor>\n");
                    writeJNLP.write("   <description kind='one-line'>" + XMLUtil.toElementContent(oneline)
                            + "</description>\n");
                    writeJNLP.write("   <description kind='short'>" + XMLUtil.toElementContent(shrt)
                            + "</description>\n");
                    writeJNLP.write("  </information>\n");

                    String realPermissions = permissions;
                    if ((jarConfig != null) && (jarConfig.getExtraManifestAttributes() != null)) {
                        String jarPermissions = jarConfig.getExtraManifestAttributes().getValue("Permissions");

                        if (jarPermissions != null) {
                            if ("all-permissions".equals(jarPermissions)) {
                                realPermissions = "<security><all-permissions/></security>\n";
                            } else {
                                realPermissions = "";
                            }
                        }
                    }

                    writeJNLP.write(realPermissions);

                    if (osDep == null) {
                        writeJNLP.write("  <resources>\n");
                    } else {
                        writeJNLP.write("  <resources os='" + osDep + "'>\n");
                    }
                    writeJNLP.write("<property name=\"jnlp.packEnabled\" value=\"" + String.valueOf(pack200)
                            + "\"/>\n");
                    writeJNLP.write(constructJarHref(jar, dashcnb));

                    processExtensions(jar, theJar.getManifest(), writeJNLP, dashcnb, codebase, realPermissions);
                    processIndirectJars(writeJNLP, dashcnb);
                    processIndirectFiles(writeJNLP, dashcnb);

                    writeJNLP.write("  </resources>\n");

                    if (useAllLocales || !declaredLocales.isEmpty()) {

                        // write down locales
                        for (Map.Entry<String, List<File>> e : localizedFiles.entrySet()) {
                            final String locale = e.getKey();

                            if (!declaredLocales.isEmpty() && !declaredLocales.contains(locale)) {
                                continue;
                            }

                            final List<File> allFiles = e.getValue();

                            writeJNLP.write("  <resources locale='" + locale + "'>\n");

                            for (File n : allFiles) {
                                log("generating locale " + locale + " for " + n, Project.MSG_VERBOSE);
                                String name = n.getName();
                                String clusterRootPrefix = jar.getParent() + File.separatorChar;
                                String absname = n.getAbsolutePath();
                                if (absname.startsWith(clusterRootPrefix)) {
                                    name = absname.substring(clusterRootPrefix.length())
                                            .replace(File.separatorChar, '-');
                                }
                                File t = new File(new File(targetFile, dashcnb), name);
                                signOrCopy(n, t);
                                writeJNLP.write(constructJarHref(n, dashcnb, name));
                            }

                            writeJNLP.write("  </resources>\n");

                        }
                    }

                    writeJNLP.write("  <component-desc/>\n");
                    writeJNLP.write("</jnlp>\n");
                    writeJNLP.close();

                    // +p
                    Files.write(writeJNLP.toString(), jnlp, Charset.forName("UTF-8"));
                } catch (Exception e) {
                    exceptions.add(new BuildException(e));
                } finally {
                    if (theJar != null) {
                        try {
                            theJar.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        });
    }

    executorService.shutdown();

    try {
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (Exception e) {
        throw new BuildException(e);
    }

    if (!exceptions.isEmpty()) {
        throw exceptions.get(0);
    }
}

From source file:org.openmrs.module.web.WebModuleUtil.java

/**
 * Performs the webapp specific startup needs for modules Normal startup is done in
 * {@link ModuleFactory#startModule(Module)} If delayContextRefresh is true, the spring context
 * is not rerun. This will save a lot of time, but it also means that the calling method is
 * responsible for restarting the context if necessary (the calling method will also have to
 * call {@link #loadServlets(Module, ServletContext)} and
 * {@link #loadFilters(Module, ServletContext)}).<br>
 * <br>//www . j  av  a  2s .co  m
 * If delayContextRefresh is true and this module should have caused a context refresh, a true
 * value is returned. Otherwise, false is returned
 *
 * @param mod Module to start
 * @param servletContext the current ServletContext
 * @param delayContextRefresh true/false whether or not to do the context refresh
 * @return boolean whether or not the spring context need to be refreshed
 */
public static boolean startModule(Module mod, ServletContext servletContext, boolean delayContextRefresh) {

    if (log.isDebugEnabled()) {
        log.debug("trying to start module " + mod);
    }

    // only try and start this module if the api started it without a
    // problem.
    if (ModuleFactory.isModuleStarted(mod) && !mod.hasStartupError()) {

        String realPath = getRealPath(servletContext);

        if (realPath == null) {
            realPath = System.getProperty("user.dir");
        }

        File webInf = new File(realPath + "/WEB-INF".replace("/", File.separator));
        if (!webInf.exists()) {
            webInf.mkdir();
        }

        copyModuleMessagesIntoWebapp(mod, realPath);
        log.debug("Done copying messages");

        // flag to tell whether we added any xml/dwr/etc changes that necessitate a refresh
        // of the web application context
        boolean moduleNeedsContextRefresh = false;

        // copy the html files into the webapp (from /web/module/ in the module)
        // also looks for a spring context file. If found, schedules spring to be restarted
        JarFile jarFile = null;
        OutputStream outStream = null;
        InputStream inStream = null;
        try {
            File modFile = mod.getFile();
            jarFile = new JarFile(modFile);
            Enumeration<JarEntry> entries = jarFile.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                log.debug("Entry name: " + name);
                if (name.startsWith("web/module/")) {
                    // trim out the starting path of "web/module/"
                    String filepath = name.substring(11);

                    StringBuffer absPath = new StringBuffer(realPath + "/WEB-INF");

                    // If this is within the tag file directory, copy it into /WEB-INF/tags/module/moduleId/...
                    if (filepath.startsWith("tags/")) {
                        filepath = filepath.substring(5);
                        absPath.append("/tags/module/");
                    }
                    // Otherwise, copy it into /WEB-INF/view/module/moduleId/...
                    else {
                        absPath.append("/view/module/");
                    }

                    // if a module id has a . in it, we should treat that as a /, i.e. files in the module
                    // ui.springmvc should go in folder names like .../ui/springmvc/...
                    absPath.append(mod.getModuleIdAsPath() + "/" + filepath);
                    if (log.isDebugEnabled()) {
                        log.debug("Moving file from: " + name + " to " + absPath);
                    }

                    // get the output file
                    File outFile = new File(absPath.toString().replace("/", File.separator));
                    if (entry.isDirectory()) {
                        if (!outFile.exists()) {
                            outFile.mkdirs();
                        }
                    } else {
                        // make the parent directories in case it doesn't exist
                        File parentDir = outFile.getParentFile();
                        if (!parentDir.exists()) {
                            parentDir.mkdirs();
                        }

                        //if (outFile.getName().endsWith(".jsp") == false)
                        //   outFile = new File(absPath.replace("/", File.separator) + MODULE_NON_JSP_EXTENSION);

                        // copy the contents over to the webapp for non directories
                        outStream = new FileOutputStream(outFile, false);
                        inStream = jarFile.getInputStream(entry);
                        OpenmrsUtil.copyFile(inStream, outStream);
                    }
                } else if (name.equals("moduleApplicationContext.xml")
                        || name.equals("webModuleApplicationContext.xml")) {
                    moduleNeedsContextRefresh = true;
                } else if (name.equals(mod.getModuleId() + "Context.xml")) {
                    String msg = "DEPRECATED: '" + name
                            + "' should be named 'moduleApplicationContext.xml' now. Please update/upgrade. ";
                    throw new ModuleException(msg, mod.getModuleId());
                }
            }
        } catch (IOException io) {
            log.warn("Unable to copy files from module " + mod.getModuleId() + " to the web layer", io);
        } finally {
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException io) {
                    log.warn("Couldn't close jar file: " + jarFile.getName(), io);
                }
            }
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException io) {
                    log.warn("Couldn't close InputStream: " + io);
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException io) {
                    log.warn("Couldn't close OutputStream: " + io);
                }
            }
        }

        // find and add the dwr code to the dwr-modules.xml file (if defined)
        InputStream inputStream = null;
        try {
            Document config = mod.getConfig();
            Element root = config.getDocumentElement();
            if (root.getElementsByTagName("dwr").getLength() > 0) {

                // get the dwr-module.xml file that we're appending our code to
                File f = new File(realPath + "/WEB-INF/dwr-modules.xml".replace("/", File.separator));

                // testing if file exists
                if (!f.exists()) {
                    // if it does not -> needs to be created
                    createDwrModulesXml(realPath);
                }

                inputStream = new FileInputStream(f);
                Document dwrmodulexml = getDWRModuleXML(inputStream, realPath);
                Element outputRoot = dwrmodulexml.getDocumentElement();

                // loop over all of the children of the "dwr" tag
                Node node = root.getElementsByTagName("dwr").item(0);
                Node current = node.getFirstChild();

                while (current != null) {
                    if ("allow".equals(current.getNodeName()) || "signatures".equals(current.getNodeName())
                            || "init".equals(current.getNodeName())) {
                        ((Element) current).setAttribute("moduleId", mod.getModuleId());
                        outputRoot.appendChild(dwrmodulexml.importNode(current, true));
                    }

                    current = current.getNextSibling();
                }

                moduleNeedsContextRefresh = true;

                // save the dwr-modules.xml file.
                OpenmrsUtil.saveDocument(dwrmodulexml, f);
            }
        } catch (FileNotFoundException e) {
            throw new ModuleException(realPath + "/WEB-INF/dwr-modules.xml file doesn't exist.", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException io) {
                    log.error("Error while closing input stream", io);
                }
            }
        }

        // mark to delete the entire module web directory on exit
        // this will usually only be used when an improper shutdown has occurred.
        String folderPath = realPath + "/WEB-INF/view/module/" + mod.getModuleIdAsPath();
        File outFile = new File(folderPath.replace("/", File.separator));
        outFile.deleteOnExit();

        // additional checks on module needing a context refresh
        if (moduleNeedsContextRefresh == false && mod.getAdvicePoints() != null
                && mod.getAdvicePoints().size() > 0) {

            // AOP advice points are only loaded during the context refresh now.
            // if the context hasn't been marked to be refreshed yet, mark it
            // now if this module defines some advice
            moduleNeedsContextRefresh = true;

        }

        // refresh the spring web context to get the just-created xml
        // files into it (if we copied an xml file)
        if (moduleNeedsContextRefresh && delayContextRefresh == false) {
            if (log.isDebugEnabled()) {
                log.debug("Refreshing context for module" + mod);
            }

            try {
                refreshWAC(servletContext, false, mod);
                log.debug("Done Refreshing WAC");
            } catch (Exception e) {
                String msg = "Unable to refresh the WebApplicationContext";
                mod.setStartupErrorMessage(msg, e);

                if (log.isWarnEnabled()) {
                    log.warn(msg + " for module: " + mod.getModuleId(), e);
                }

                try {
                    stopModule(mod, servletContext, true);
                    ModuleFactory.stopModule(mod, true, true); //remove jar from classloader play
                } catch (Exception e2) {
                    // exception expected with most modules here
                    if (log.isWarnEnabled()) {
                        log.warn("Error while stopping a module that had an error on refreshWAC", e2);
                    }
                }

                // try starting the application context again
                refreshWAC(servletContext, false, mod);

                notifySuperUsersAboutModuleFailure(mod);
            }

        }

        if (!delayContextRefresh && ModuleFactory.isModuleStarted(mod)) {
            // only loading the servlets/filters if spring is refreshed because one
            // might depend on files being available in spring
            // if the caller wanted to delay the refresh then they are responsible for
            // calling these two methods on the module

            // find and cache the module's servlets
            //(only if the module started successfully previously)
            log.debug("Loading servlets and filters for module: " + mod);
            loadServlets(mod, servletContext);
            loadFilters(mod, servletContext);
        }

        // return true if the module needs a context refresh and we didn't do it here
        return (moduleNeedsContextRefresh && delayContextRefresh == true);

    }

    // we aren't processing this module, so a context refresh is not necessary
    return false;
}

From source file:org.openspaces.pu.container.standalone.StandaloneProcessingUnitContainerProvider.java

/**
 * <p> Creates a new {@link StandaloneProcessingUnitContainer} based on the configured
 * parameters. A standalone processing unit container is a container that understands a
 * processing unit archive structure (both when working with an "exploded" directory and when
 * working with a zip/jar archive of it). It is provided with the location of the processing
 * unit using {@link org.openspaces.pu.container.standalone.StandaloneProcessingUnitContainerProvider#StandaloneProcessingUnitContainerProvider(String)}.
 * The location itself follows Spring resource loader syntax.
 *
 * <p> If {@link #addConfigLocation(String)} is used, the Spring xml context will be read based
 * on the provided locations. If no config location was provided the default config location
 * will be <code>classpath*:/META-INF/spring/pu.xml</code>.
 *
 * <p> If {@link #setBeanLevelProperties(org.openspaces.core.properties.BeanLevelProperties)} is
 * set will use the configured bean level properties in order to configure the application
 * context and specific beans within it based on properties. This is done by adding {@link
 * org.openspaces.core.properties.BeanLevelPropertyBeanPostProcessor} and {@link
 * org.openspaces.core.properties.BeanLevelPropertyPlaceholderConfigurer} to the application
 * context.//from   w  w w .  j  a  v  a 2s  .c o m
 *
 * <p> If {@link #setClusterInfo(org.openspaces.core.cluster.ClusterInfo)} is set will use it to
 * inject {@link org.openspaces.core.cluster.ClusterInfo} into beans that implement {@link
 * org.openspaces.core.cluster.ClusterInfoAware}.
 *
 * @return An {@link StandaloneProcessingUnitContainer} instance
 */
public ProcessingUnitContainer createContainer() throws CannotCreateContainerException {
    File fileLocation = new File(location);
    if (!fileLocation.exists()) {
        throw new CannotCreateContainerException("Failed to locate pu location [" + location + "]");
    }

    // in case we don't have a cluster info specific members
    final ClusterInfo clusterInfo = getClusterInfo();
    if (clusterInfo != null && clusterInfo.getInstanceId() == null) {
        ClusterInfo origClusterInfo = clusterInfo;
        List<ProcessingUnitContainer> containers = new ArrayList<ProcessingUnitContainer>();
        for (int i = 0; i < clusterInfo.getNumberOfInstances(); i++) {
            ClusterInfo containerClusterInfo = clusterInfo.copy();
            containerClusterInfo.setInstanceId(i + 1);
            containerClusterInfo.setBackupId(null);
            setClusterInfo(containerClusterInfo);
            containers.add(createContainer());
            if (clusterInfo.getNumberOfBackups() != null) {
                for (int j = 0; j < clusterInfo.getNumberOfBackups(); j++) {
                    containerClusterInfo = containerClusterInfo.copy();
                    containerClusterInfo.setBackupId(j + 1);
                    setClusterInfo(containerClusterInfo);
                    containers.add(createContainer());
                }
            }
        }
        setClusterInfo(origClusterInfo);
        return new CompoundProcessingUnitContainer(
                containers.toArray(new ProcessingUnitContainer[containers.size()]));
    }

    if (clusterInfo != null) {
        ClusterInfoParser.guessSchema(clusterInfo);
    }

    if (logger.isInfoEnabled()) {
        logger.info("Starting a Standalone processing unit container "
                + (clusterInfo != null ? "with " + clusterInfo : ""));
    }

    List<URL> urls = new ArrayList<URL>();
    List<URL> sharedUrls = new ArrayList<URL>();
    if (fileLocation.isDirectory()) {
        if (fileLocation.exists()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Adding pu directory location [" + location + "] to classpath");
            }
            try {
                urls.add(fileLocation.toURL());
            } catch (MalformedURLException e) {
                throw new CannotCreateContainerException(
                        "Failed to add classes to class loader with location [" + location + "]", e);
            }
        }
        addJarsLocation(fileLocation, urls, "lib");
        addJarsLocation(fileLocation, sharedUrls, "shared-lib");
    } else {
        JarFile jarFile;
        try {
            jarFile = new JarFile(fileLocation);
        } catch (IOException e) {
            throw new CannotCreateContainerException("Failed to open pu file [" + location + "]", e);
        }
        // add the root to the classpath
        try {
            urls.add(new URL("jar:" + fileLocation.toURL() + "!/"));
        } catch (MalformedURLException e) {
            throw new CannotCreateContainerException(
                    "Failed to add pu location [" + location + "] to classpath", e);
        }
        // add jars in lib and shared-lib to the classpath
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry jarEntry = entries.nextElement();
            if (isWithinDir(jarEntry, "lib") || isWithinDir(jarEntry, "shared-lib")) {
                // extract the jar into a temp location
                if (logger.isDebugEnabled()) {
                    logger.debug("Adding jar [" + jarEntry.getName() + "] with pu location [" + location + "]");
                }
                File tempLocation = new File(System.getProperty("java.io.tmpdir") + "/openspaces");
                tempLocation.mkdirs();
                File tempJar;
                String tempJarName = jarEntry.getName();
                if (tempJarName.indexOf('/') != -1) {
                    tempJarName = tempJarName.substring(tempJarName.lastIndexOf('/') + 1);
                }
                try {
                    tempJar = File.createTempFile(tempJarName, ".jar", tempLocation);
                } catch (IOException e) {
                    throw new CannotCreateContainerException("Failed to create temp jar at location ["
                            + tempLocation + "] with name [" + tempJarName + "]", e);
                }
                tempJar.deleteOnExit();
                if (logger.isTraceEnabled()) {
                    logger.trace("Extracting jar [" + jarEntry.getName() + "] to temporary jar ["
                            + tempJar.getAbsolutePath() + "]");
                }

                FileOutputStream fos;
                try {
                    fos = new FileOutputStream(tempJar);
                } catch (FileNotFoundException e) {
                    throw new CannotCreateContainerException(
                            "Failed to find temp jar [" + tempJar.getAbsolutePath() + "]", e);
                }
                InputStream is = null;
                try {
                    is = jarFile.getInputStream(jarEntry);
                    FileCopyUtils.copy(is, fos);
                } catch (IOException e) {
                    throw new CannotCreateContainerException(
                            "Failed to create temp jar [" + tempJar.getAbsolutePath() + "]");
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e1) {
                            // do nothing
                        }
                    }
                    try {
                        fos.close();
                    } catch (IOException e1) {
                        // do nothing
                    }
                }

                try {
                    if (isWithinDir(jarEntry, "lib")) {
                        urls.add(tempJar.toURL());
                    } else if (isWithinDir(jarEntry, "shared-lib")) {
                        sharedUrls.add(tempJar.toURL());
                    }
                } catch (MalformedURLException e) {
                    throw new CannotCreateContainerException("Failed to add pu entry [" + jarEntry.getName()
                            + "] with location [" + location + "]", e);
                }
            }
        }
    }

    List<URL> allUrls = new ArrayList<URL>();
    allUrls.addAll(sharedUrls);
    allUrls.addAll(urls);

    addUrlsToContextClassLoader(allUrls.toArray(new URL[allUrls.size()]));

    StandaloneContainerRunnable containerRunnable = new StandaloneContainerRunnable(getBeanLevelProperties(),
            clusterInfo, configLocations);
    Thread standaloneContainerThread = new Thread(containerRunnable, "Standalone Container Thread");
    standaloneContainerThread.setDaemon(false);
    standaloneContainerThread.start();

    while (!containerRunnable.isInitialized()) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            logger.warn("Interrupted while waiting for standalone container to initialize");
        }
    }

    if (containerRunnable.hasException()) {
        throw new CannotCreateContainerException("Failed to start container", containerRunnable.getException());
    }

    return new StandaloneProcessingUnitContainer(containerRunnable);
}

From source file:org.openmrs.module.ModuleFileParser.java

/**
 * load in messages/*from ww  w  . j a v  a  2s  .c o m*/
 *
 * @param root
 * @param configVersion
 * @return
 */
private Map<String, Properties> getMessages(Element root, String configVersion, JarFile jarfile,
        String moduleId, String version) {

    Map<String, Properties> messages = new HashMap<String, Properties>();

    NodeList messageNodes = root.getElementsByTagName("messages");
    if (messageNodes.getLength() > 0) {
        log.debug("# message nodes: " + messageNodes.getLength());
        int i = 0;
        while (i < messageNodes.getLength()) {
            Node node = messageNodes.item(i);
            NodeList nodes = node.getChildNodes();
            int x = 0;
            String lang = "", file = "";
            while (x < nodes.getLength()) {
                Node childNode = nodes.item(x);
                if ("lang".equals(childNode.getNodeName())) {
                    lang = childNode.getTextContent().trim();
                } else if ("file".equals(childNode.getNodeName())) {
                    file = childNode.getTextContent().trim();
                }
                x++;
            }
            log.debug("lang: " + lang + " file: " + file);

            // lang and file are required
            if (lang.length() > 0 && file.length() > 0) {
                InputStream inStream = null;
                try {
                    //if in development mode, load message properties file from the root dev folder
                    File devDir = ModuleUtil.getDevelopmentDirectory(moduleId);
                    if (devDir != null) {
                        File pathName = new File(devDir, "api" + File.separator + "target" + File.separator
                                + "classes" + File.separator + file);
                        inStream = new FileInputStream(pathName);
                    } else {
                        inStream = ModuleUtil.getResourceFromApi(jarfile, moduleId, version, file);
                    }

                    if (inStream == null) {
                        // Try the old way. Loading from the root of the omod
                        ZipEntry entry = jarfile.getEntry(file);
                        if (entry == null) {
                            throw new ModuleException(Context.getMessageSourceService().getMessage(
                                    "Module.error.noMessagePropsFile", new Object[] { file, lang },
                                    Context.getLocale()));
                        }
                        inStream = jarfile.getInputStream(entry);
                    }
                    Properties props = new Properties();
                    OpenmrsUtil.loadProperties(props, inStream);
                    messages.put(lang, props);
                } catch (IOException e) {
                    log.warn("Unable to load properties: " + file);
                } finally {
                    IOUtils.closeQuietly(inStream);
                }
            } else {
                log.warn("'lang' and 'file' are required for extensions. Given '" + lang + "' and '" + file
                        + "'");
            }
            i++;
        }
    }

    return messages;
}

From source file:org.olat.core.util.i18n.I18nManager.java

/**
 * Copy the given set of languages from the given jar to the configured i18n
 * source directories. This method can only be called in a translation
 * server environment./*from   w  w  w  . j a va 2 s .c om*/
 * 
 * @param jarFile
 * @param toCopyI18nKeys
 */
public void copyLanguagesFromJar(File jarFile, Collection<String> toCopyI18nKeys) {
    if (!I18nModule.isTransToolEnabled()) {
        throw new AssertException(
                "Programming error - can only copy i18n files from a language pack to the source when in translation mode");
    }
    JarFile jar = null;
    try {
        jar = new JarFile(jarFile);
        Enumeration<JarEntry> jarEntries = jar.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            String jarEntryName = jarEntry.getName();
            // Check if this entry is a language file
            for (String i18nKey : toCopyI18nKeys) {
                if (jarEntryName.endsWith(I18N_DIRNAME + "/" + I18nModule.LOCAL_STRINGS_FILE_PREFIX + i18nKey
                        + I18nModule.LOCAL_STRINGS_FILE_POSTFIX)) {
                    File targetBaseDir;
                    if (i18nKey.equals("de") || i18nKey.equals("en")) {
                        targetBaseDir = I18nModule.getTransToolApplicationLanguagesSrcDir();
                    } else {
                        targetBaseDir = I18nModule.getTransToolApplicationOptLanguagesSrcDir();
                    }
                    // Copy file
                    File targetFile = new File(targetBaseDir, jarEntryName);
                    targetFile.getParentFile().mkdirs();
                    FileUtils.save(jar.getInputStream(jarEntry), targetFile);
                    // Check that saved properties file is empty, if so remove it 
                    Properties props = new Properties();
                    props.load(new FileInputStream(targetFile));
                    if (props.size() == 0) {
                        targetFile.delete();
                        // Delete empty parent dirs recursively
                        File parent = targetFile.getParentFile();
                        while (parent != null && parent.list() != null && parent.list().length == 0) {
                            parent.delete();
                            parent = parent.getParentFile();
                        }
                    }
                    // Continue with next jar entry
                    break;
                }
            }
        }
    } catch (IOException e) {
        throw new OLATRuntimeException(
                "Error when copying up i18n files from a jar::" + jarFile.getAbsolutePath(), e);
    } finally {
        IOUtils.closeQuietly(jar);
    }
}

From source file:JNLPAppletLauncher.java

/**
 * Extract the specified set of native libraries in the given jar file.
 */// w  ww . j  a  v a 2s  . co m
private void extractNativeLibs(JarFile jarFile, Set/*<String>*/ rootEntries, Set/*<String>*/ nativeLibNames)
        throws IOException {

    if (DEBUG) {
        System.err.println("extractNativeLibs:");
    }

    Enumeration/*<JarEntry>*/ entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String entryName = entry.getName();

        if (VERBOSE) {
            System.err.println("JarEntry : " + entryName);
        }

        // In order to be compatible with Java Web Start, we need
        // to extract all root entries from the jar file. However,
        // we only allow direct loading of the previously
        // discovered native library names.
        if (rootEntries.contains(entryName)) {
            // strip prefix & suffix
            String libName = entryName.substring(nativePrefix.length(),
                    entryName.length() - nativeSuffix.length());
            if (DEBUG) {
                System.err.println("EXTRACT: " + entryName + "(" + libName + ")");
            }

            File nativeLib = new File(nativeTmpDir, entryName);
            InputStream in = new BufferedInputStream(jarFile.getInputStream(entry));
            OutputStream out = new BufferedOutputStream(new FileOutputStream(nativeLib));
            int numBytesWritten = copyStream(in, out, -1);
            in.close();
            out.close();
            if (nativeLibNames.contains(entryName)) {
                nativeLibMap.put(libName, nativeLib.getAbsolutePath());
            }
        }
    }
}

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

public static String getRClassForBean(JarFile jarFile, String beanClassName) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(
            jarFile.getInputStream(jarFile.getEntry(beanClassName.replace('.', '/') + ".java"))));
    do {//from www. ja v  a 2  s.co  m
        String line = br.readLine();
        if (line != null) {
            int p = line.indexOf(LOC_STR_LEFT);
            if (p != -1) {
                return line.substring(p + LOC_STR_LEFT.length(), line.indexOf(LOC_STR_RIGHT)).trim();
            }
        } else
            break;
    } while (true);
    return null;
}