Example usage for java.util.jar JarFile getEntry

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

Introduction

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

Prototype

public ZipEntry getEntry(String name) 

Source Link

Document

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

Usage

From source file:com.liferay.ide.ui.editor.LiferayPropertiesSourceViewerConfiguration.java

@Override
public IContentAssistant getContentAssistant(final ISourceViewer sourceViewer) {
    if (this.propKeys == null) {
        final IEditorInput input = this.getEditor().getEditorInput();

        // first fine runtime location to get properties definitions
        final IPath appServerPortalDir = getAppServerPortalDir(input);
        final String propertiesEntry = getPropertiesEntry(input);

        PropKey[] keys = null;/*from w  w  w  . ja va  2  s. co  m*/

        if (appServerPortalDir != null && appServerPortalDir.toFile().exists()) {
            try {
                final JarFile jar = new JarFile(
                        appServerPortalDir.append("WEB-INF/lib/portal-impl.jar").toFile());
                final ZipEntry lang = jar.getEntry(propertiesEntry);

                keys = parseKeys(jar.getInputStream(lang));

                jar.close();
            } catch (Exception e) {
                LiferayUIPlugin.logError("Unable to get portal properties file", e);
            }
        } else {
            return assitant;
        }

        final Object adapter = input.getAdapter(IFile.class);

        if (adapter instanceof IFile && isHookProject(((IFile) adapter).getProject())) {
            final ILiferayProject liferayProject = LiferayCore.create(((IFile) adapter).getProject());
            final ILiferayPortal portal = liferayProject.adapt(ILiferayPortal.class);

            if (portal != null) {
                final Set<String> hookProps = new HashSet<String>();
                Collections.addAll(hookProps, portal.getHookSupportedProperties());

                final List<PropKey> filtered = new ArrayList<PropKey>();

                for (PropKey pk : keys) {
                    if (hookProps.contains(pk.getKey())) {
                        filtered.add(pk);
                    }
                }

                keys = filtered.toArray(new PropKey[0]);
            }
        }

        propKeys = keys;
    }

    if (propKeys != null && assitant == null) {
        final ContentAssistant ca = new ContentAssistant() {
            @Override
            public IContentAssistProcessor getContentAssistProcessor(final String contentType) {
                return new LiferayPropertiesContentAssistProcessor(propKeys, contentType);
            }
        };

        ca.setInformationControlCreator(getInformationControlCreator(sourceViewer));

        assitant = ca;
    }

    return assitant;
}

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

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {

    if (this.classPath == null) {
        throw new ClassNotFoundException("invalid search root: " + this.classPath);
    } else if (name == null) {
        throw new ClassNotFoundException(MessageResource.NULL_CLASS.getMessage());
    }//from   www  .j a  v  a2 s.co  m

    String classNamePath = name.replace('.', '/') + ".class";

    byte[] fileBytes = null;
    try {
        InputStream is = null;
        JarFile jarFile = null;

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

                if (ze != null) {
                    is = jarFile.getInputStream(ze);
                    break;
                } else {
                    jarFile.close();
                }
            } else {
                Resource classFile = entry.createRelative(classNamePath);
                if (classFile.exists()) {
                    is = classFile.getInputStream();
                    break;
                }
            }
        }

        if (is != null) {
            try {
                fileBytes = IOUtils.toByteArray(is);
                is.close();
            } finally {
                if (jarFile != null) {
                    jarFile.close();
                }
            }
        }
    } catch (IOException e) {
        throw new ClassNotFoundException(e.getMessage(), e);
    }

    if (name.contains(".")) {
        String packageName = name.substring(0, name.lastIndexOf('.'));
        if (getPackage(packageName) == null) {
            definePackage(packageName, "", "", "", "", "", "", null);
        }
    }

    Class<?> ret;
    if (fileBytes == null) {
        ret = ClassLoaderUtils.loadClass(name, this.parentClassLoader);
    } else {
        ret = defineClass(name, fileBytes, 0, fileBytes.length);
    }

    if (ret == null) {
        throw new ClassNotFoundException(
                "Couldn't find class " + name + " in expected classpath: " + this.classPath);
    }

    return ret;
}

From source file:com.wavemaker.common.util.ThrowawayFileClassLoader.java

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {

    if (this.classPath == null) {
        throw new ClassNotFoundException("invalid search root: " + this.classPath);
    } else if (name == null) {
        throw new ClassNotFoundException(MessageResource.NULL_CLASS.getMessage());
    }/*w ww . ja  v  a 2 s .com*/

    String classNamePath = name.replace('.', '/') + ".class";

    byte[] fileBytes = null;
    try {
        InputStream is = null;
        JarFile jarFile = null;

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

                if (ze != null) {
                    is = jarFile.getInputStream(ze);
                    break;
                } else {
                    jarFile.close();
                }
            } else {

                Resource classFile = entry.createRelative(classNamePath);
                if (classFile.exists()) {
                    is = classFile.getInputStream();
                    break;
                }
            }
        }

        if (is != null) {
            try {
                fileBytes = IOUtils.toByteArray(is);
                is.close();
            } finally {
                if (jarFile != null) {
                    jarFile.close();
                }
            }
        }
    } catch (IOException e) {
        throw new ClassNotFoundException(e.getMessage(), e);
    }

    if (name.contains(".")) {
        String packageName = name.substring(0, name.lastIndexOf('.'));
        if (getPackage(packageName) == null) {
            definePackage(packageName, "", "", "", "", "", "", null);
        }
    }

    Class<?> ret;
    if (fileBytes == null) {
        ret = ClassLoaderUtils.loadClass(name, this.parentClassLoader);
    } else {
        ret = defineClass(name, fileBytes, 0, fileBytes.length);
    }

    if (ret == null) {
        throw new ClassNotFoundException(
                "Couldn't find class " + name + " in expected classpath: " + this.classPath);
    }

    return ret;
}

From source file:org.springframework.extensions.config.source.UrlConfigSource.java

/**
 * Processes the given JAR file pattern source. The classpath
 * will be searched for JAR files that contain files that match
 * the given pattern./*from   w  w  w .  java2s . c o  m*/
 * 
 * NOTE: Currently only files within the META-INF folder are supported
 * i.e. patterns that look like "jar:*!/META-INF/[filename]"
 * 
 * @param sourcePattern The wildcard pattern for files to find within JARs
 */
protected void processWildcardJarSource(String sourcePattern) {
    String file = sourcePattern.substring(7);

    if (file.startsWith(META_INF) == false) {
        throw new UnsupportedOperationException(
                "Only JAR file wildcard searches within the META-INF folder are currently supported");
    }

    try {
        if (applicationContext == null) {
            // get a list of all the JAR files that have the META-INF folder
            Enumeration<URL> urls = this.getClass().getClassLoader().getResources(META_INF);
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                // only add the item if is a reference to a JAR file
                if (url.getProtocol().equals(JarConfigSource.JAR_PROTOCOL)) {
                    URLConnection conn = url.openConnection();
                    if (conn instanceof JarURLConnection) {
                        // open the jar file and see if it contains what we're looking for
                        JarURLConnection jarConn = (JarURLConnection) conn;
                        JarFile jar = ((JarURLConnection) conn).getJarFile();
                        ZipEntry entry = jar.getEntry(file);
                        if (entry != null) {
                            if (logger.isInfoEnabled())
                                logger.info("Found " + file + " in " + jarConn.getJarFileURL());

                            String sourceString = JarConfigSource.JAR_PROTOCOL + ":"
                                    + jarConn.getJarFileURL().toExternalForm()
                                    + JarConfigSource.JAR_PATH_SEPARATOR + file;

                            super.addSourceString(sourceString);
                        } else if (logger.isDebugEnabled()) {
                            logger.debug("Did not find " + file + " in " + jarConn.getJarFileURL());
                        }
                    }
                }
            }
        } else {
            Resource[] resources = applicationContext.getResources(PREFIX_CLASSPATH_ALL + file);

            for (Resource resource : resources) {
                URL resourceUrl = resource.getURL();
                if (ResourceUtils.isJarURL(resourceUrl)
                        || ResourceUtils.URL_PROTOCOL_VFSZIP.equals(resourceUrl.getProtocol())) {
                    URL jarURL = extractJarFileURL(resourceUrl);

                    String sourceString = JarConfigSource.JAR_PROTOCOL + ":" + jarURL.toString()
                            + JarConfigSource.JAR_PATH_SEPARATOR + file;

                    super.addSourceString(sourceString);
                } else if (ResourceUtils.URL_PROTOCOL_VFS.equals(resourceUrl.getProtocol())) {
                    super.addSourceString(resourceUrl.toString());
                }
            }
        }
    } catch (IOException ioe) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to process JAR file wildcard: " + sourcePattern, ioe);
    }
}

From source file:org.jasig.portal.plugin.deployer.AbstractExtractingEarDeployer.java

/**
 * Gets the EAR descriptor from the {@link JarFile}.
 * // w  w w.jav  a  2s .  c  o  m
 * @param earFile The EAR to get the descriptor from.
 * @return The descriptor DOM for the EAR.
 * @throws IOException If there is any problem reading the descriptor from the EAR.
 */
protected Document getDescriptorDom(final JarFile earFile) throws MojoFailureException {
    final ZipEntry descriptorEntry = earFile.getEntry(DESCRIPTOR_PATH);
    if (descriptorEntry == null) {
        throw new IllegalArgumentException(
                "JarFile '" + earFile + "' does not contain a descriptor at '" + DESCRIPTOR_PATH + "'");
    }

    InputStream descriptorStream = null;
    try {
        descriptorStream = earFile.getInputStream(descriptorEntry);

        final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

        final DocumentBuilder docBuilder;
        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException pce) {
            throw new RuntimeException("Failed to create DocumentBuilder to parse EAR descriptor.", pce);
        }

        docBuilder.setEntityResolver(new ClasspathEntityResolver(this.getLogger()));

        final Document descriptorDom;
        try {
            descriptorDom = docBuilder.parse(descriptorStream);
            return descriptorDom;
        } catch (SAXException e) {
            throw new MojoFailureException(
                    "Failed to parse descriptor '" + DESCRIPTOR_PATH + "' from EAR '" + earFile.getName() + "'",
                    e);
        }
    } catch (IOException e) {
        throw new MojoFailureException(
                "Failed to read descriptor '" + DESCRIPTOR_PATH + "' from EAR '" + earFile.getName() + "'", e);
    } finally {
        IOUtils.closeQuietly(descriptorStream);
    }
}

From source file:org.amanzi.awe.scripting.utils.ScriptUtils.java

/**
 * first check for version folder in jar file. if jar folder not exist -> check for directory in
 * folderPath/*from   w  w w .j a  v a 2s  . c  o  m*/
 * 
 * @param jarFile
 * @param version
 * @param version2
 */
private boolean checkFileExisting(final JarFile jarFile, final String folderPath, final String versionFolder) {
    if (jarFile == null) {
        if (new File(folderPath + versionFolder).isDirectory()) {
            return true;
        }
    } else if (jarFile.getEntry(versionFolder) != null) {
        return true;
    }
    return false;
}

From source file:org.jsweet.transpiler.candies.CandyDescriptor.java

public static CandyDescriptor fromCandyJar(JarFile jarFile, String jsOutputDirPath) throws IOException {
    JarEntry pomEntry = null;//from  ww  w .  j a v a 2 s.  co m
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry current = entries.nextElement();
        if (current.getName().endsWith("pom.xml")) {
            pomEntry = current;
        }
    }

    String pomContent = IOUtils.toString(jarFile.getInputStream(pomEntry));

    // take only general part
    int dependenciesIndex = pomContent.indexOf("<dependencies>");
    String pomGeneralPart = dependenciesIndex > 0 ? pomContent.substring(0, dependenciesIndex) : pomContent;

    // extract candy model version from <groupId></groupId>
    Matcher matcher = MODEL_VERSION_PATTERN.matcher(pomGeneralPart);
    String modelVersion = "unknown";
    if (matcher.find()) {
        modelVersion = matcher.group(1);
    }

    // extract name from <artifactId></artifactId>
    matcher = ARTIFACT_ID_PATTERN.matcher(pomGeneralPart);
    String name = "unknown";
    if (matcher.find()) {
        name = matcher.group(1);
    }

    matcher = VERSION_PATTERN.matcher(pomGeneralPart);
    String version = "unknown";
    if (matcher.find()) {
        version = matcher.group(1);
    }

    long lastUpdateTimestamp = jarFile.getEntry("META-INF/MANIFEST.MF").getTime();

    String transpilerVersion = null;

    ZipEntry metadataEntry = jarFile.getEntry("META-INF/candy-metadata.json");
    if (metadataEntry != null) {
        String metadataContent = IOUtils.toString(jarFile.getInputStream(metadataEntry));

        @SuppressWarnings("unchecked")
        Map<String, ?> metadata = gson.fromJson(metadataContent, Map.class);

        transpilerVersion = (String) metadata.get("transpilerVersion");
    }

    String jsDirPath = "META-INF/resources/webjars/" + name + "/" + version;
    ZipEntry jsDirEntry = jarFile.getEntry(jsDirPath);
    List<String> jsFilesPaths = new LinkedList<>();
    if (jsDirEntry != null) {
        // collects js files
        jarFile.stream() //
                .filter(entry -> entry.getName().startsWith(jsDirPath) && entry.getName().endsWith(".js")) //
                .map(entry -> entry.getName()) //
                .forEach(jsFilesPaths::add);
    }

    return new CandyDescriptor( //
            name, //
            version, //
            lastUpdateTimestamp, //
            modelVersion, //
            transpilerVersion, //
            jsOutputDirPath, //
            jsDirPath, //
            jsFilesPaths);
}

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

/**
 * Load resource from a jar inside a jar.
 * /*from   w  ww .  jav a 2 s. co m*/
 * @param outerJarFile jar file that contains a jar file
 * @param innerJarFileLocation inner jar file location relative to the outer jar
 * @param resource path to a resource relative to the inner jar
 * @return resource from the inner jar as an input stream or <code>null</code> if resource cannot be loaded
 */
private static InputStream getResourceFromInnerJar(JarFile outerJarFile, String innerJarFileLocation,
        String resource) {
    File tempFile = null;
    FileOutputStream tempOut = null;
    JarFile innerJarFile = null;
    InputStream innerInputStream = null;
    try {
        tempFile = File.createTempFile("tempFile", "jar");
        tempOut = new FileOutputStream(tempFile);
        ZipEntry innerJarFileEntry = outerJarFile.getEntry(innerJarFileLocation);
        if (innerJarFileEntry != null) {
            IOUtils.copy(outerJarFile.getInputStream(innerJarFileEntry), tempOut);
            innerJarFile = new JarFile(tempFile);
            ZipEntry targetEntry = innerJarFile.getEntry(resource);
            if (targetEntry != null) {
                // clone InputStream to make it work after the innerJarFile is closed
                innerInputStream = innerJarFile.getInputStream(targetEntry);
                byte[] byteArray = IOUtils.toByteArray(innerInputStream);
                return new ByteArrayInputStream(byteArray);
            }
        }
    } catch (IOException e) {
        log.error("Unable to get '" + resource + "' from '" + innerJarFileLocation + "' of '"
                + outerJarFile.getName() + "'", e);
    } finally {
        IOUtils.closeQuietly(tempOut);
        IOUtils.closeQuietly(innerInputStream);

        // close inner jar file before attempting to delete temporary file
        try {
            if (innerJarFile != null) {
                innerJarFile.close();
            }
        } catch (IOException e) {
            log.warn("Unable to close inner jarfile: " + innerJarFile, e);
        }

        // delete temporary file
        if (tempFile != null && !tempFile.delete()) {
            log.warn("Could not delete temporary jarfile: " + tempFile);
        }
    }
    return null;
}

From source file:org.nuxeo.runtime.deployment.preprocessor.DeploymentPreprocessor.java

protected FragmentDescriptor getJARFragment(File file) throws IOException {
    FragmentDescriptor fd = null;/*from  w  w  w  . j a v a 2s  .co  m*/
    JarFile jar = new JarFile(file);
    try {
        ZipEntry ze = jar.getEntry(FRAGMENT_FILE);
        if (ze != null) {
            InputStream in = new BufferedInputStream(jar.getInputStream(ze));
            try {
                fd = (FragmentDescriptor) xmap.load(in);
            } finally {
                in.close();
            }
            if (fd.name == null) {
                // fallback on symbolic name
                fd.name = getSymbolicName(file);
            }
            if (fd.name == null) {
                // fallback on artifact id
                fd.name = getJarArtifactName(file.getName());
            }
            if (fd.version == 0) { // compat with versions < 5.4
                processBundleForCompat(fd, file);
            }
        }
    } finally {
        jar.close();
    }
    return fd;
}

From source file:org.openmrs.module.moduledistro.api.impl.ModuleDistroServiceImpl.java

/**
  * Populates the moduleId, moduleVersion, action, and skipVersion fields on candidate
  * /*from  ww w . java 2s .co  m*/
  * @param candidate
 * @throws IOException
 *
 * @should read the id and version from config.xml 
  */
public void populateFields(UploadedModule candidate) throws IOException {
    JarFile jar = new JarFile(candidate.getData());
    ZipEntry entry = jar.getEntry("config.xml");
    if (entry == null) {
        throw new IOException("Cannot find config.xml");
    }
    StringWriter sw = new StringWriter();
    IOUtils.copy(jar.getInputStream(entry), sw);
    String configXml = sw.toString();

    String moduleId = null;
    {
        Matcher matcher = Pattern.compile("<id>(.+?)</id>").matcher(configXml);
        if (!matcher.find())
            throw new IOException("Cannot find <id>...</id> in config.xml");
        moduleId = matcher.group(1).trim();
    }

    String moduleVersion = null;
    {
        Matcher matcher = Pattern.compile("<version>(.+?)</version>").matcher(configXml);
        if (!matcher.find())
            throw new IOException("Cannot find <version>...</version> in config.xml");
        moduleVersion = matcher.group(1).trim();
    }

    candidate.setModuleId(moduleId);
    candidate.setModuleVersion(moduleVersion);

    Module existing = ModuleFactory.getModuleById(candidate.getModuleId());
    if (existing == null) {
        candidate.setAction(Action.INSTALL);
        return;
    } else { // there's an existing module
        candidate.setExisting(existing);

        if (shouldInstallNewVersion(candidate.getModuleVersion(), existing.getVersion())) {
            candidate.setAction(Action.UPGRADE);
        } else {
            candidate.setAction(Action.SKIP);
            candidate.setSkipReason(
                    "an equivalent or newer version is already installed: (" + existing.getVersion() + ")");
        }

        // if the module is up-to-date, but not running, we need to start it 
        if (!existing.isStarted() && candidate.getAction().equals(Action.SKIP)) {
            candidate.setAction(Action.START);
        }
    }

}