Example usage for java.util.jar JarFile JarFile

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

Introduction

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

Prototype

public JarFile(File file) throws IOException 

Source Link

Document

Creates a new JarFile to read from the specified File object.

Usage

From source file:com.amalto.core.jobox.component.JobAware.java

private void setClassPath4TISJob(File entity, JobInfo jobInfo) {
    String newClassPath = ""; //$NON-NLS-1$
    String separator = System.getProperty("path.separator"); //$NON-NLS-1$
    List<File> checkList = new ArrayList<File>();
    JoboxUtil.findFirstFile(null, entity, "classpath.jar", checkList); //$NON-NLS-1$
    if (checkList.size() > 0) {
        try {/*from w ww.  j av a 2  s  .co  m*/
            String basePath = checkList.get(0).getParent();
            JarFile jarFile = new JarFile(checkList.get(0).getAbsolutePath());
            Manifest jarFileManifest = jarFile.getManifest();
            String cxt = jarFileManifest.getMainAttributes().getValue("activeContext"); //$NON-NLS-1$
            jobInfo.setContextStr(cxt);
            String classPaths = jarFileManifest.getMainAttributes().getValue("Class-Path"); //$NON-NLS-1$
            String[] classPathsArray = classPaths.split("\\s+", 0); //$NON-NLS-1$
            List<String> classPathsArrayList = new ArrayList<String>(Arrays.asList(classPathsArray));
            List<String> classPathsExtArray = new ArrayList<String>();
            if (!classPathsArrayList.contains(".")) { //$NON-NLS-1$
                classPathsExtArray.add("."); //$NON-NLS-1$
            }
            if (classPathsArrayList.size() > 0) {
                classPathsExtArray.addAll(classPathsArrayList);
            }
            for (String classPath : classPathsExtArray) {
                File libFile = new File(basePath + File.separator + classPath);
                if (libFile.exists()) {
                    if (newClassPath.length() == 0) {
                        newClassPath += libFile.getAbsolutePath();
                    } else if (newClassPath.length() > 0) {
                        newClassPath += separator + libFile.getAbsolutePath();
                    }
                }
            }
        } catch (IOException e) {
            throw new JoboxException(e);
        }
    }
    jobInfo.setClasspath(newClassPath);
}

From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.TypeLibraryUtil.java

/**
 * Adding the TypeLibProtocal to the name for the xsd entry.
 *
 * @param typeLibName the type lib name//from ww w .ja v a  2  s .  com
 * @param baseLocation the base location
 * @return the dependency stream
 * @throws CoreException the core exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static InputStream getDependencyStream(String typeLibName, String baseLocation)
        throws CoreException, IOException {

    if (baseLocation.toLowerCase().startsWith("jar:file:/")) {
        JarFile jarFile = new JarFile(getJarFile(baseLocation.substring(10, baseLocation.length())));
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().startsWith(SOATypeLibraryConstants.INFO_DEP_XML_PATH_IN_JAR)
                    && entry.getName().endsWith(SOATypeLibraryConstants.FILE_TYPE_DEP_XML)) {
                return jarFile.getInputStream(entry);
            }
        }
    } else {
        IProject project = WorkspaceUtil.getProject(typeLibName);
        if (project.isAccessible() && project.hasNature(GlobalRepositorySystem.instanceOf()
                .getActiveRepositorySystem().getProjectNatureId(SupportedProjectType.TYPE_LIBRARY))) {
            return project.getFile(SOATypeLibraryConstants.FOLDER_META_SRC_META_INF
                    + WorkspaceUtil.PATH_SEPERATOR + project.getName() + WorkspaceUtil.PATH_SEPERATOR
                    + SOATypeLibraryConstants.FILE_TYPE_DEP_XML).getContents();
        }
    }
    throw new IOException("InpuStream could not be obtained with the type lib Name " + typeLibName
            + " and base location " + baseLocation);
}

From source file:io.fabric8.insight.log.support.LogQuerySupport.java

protected String jarIndex(File file) throws IOException {
    JarFile jarFile = new JarFile(file);
    return jarIndex(jarFile);
}

From source file:cn.webwheel.DefaultMain.java

/**
 * Find action method under certain package recursively.
 * <p>//from www  .j  a v  a 2  s  . c om
 * Action method must be marked by {@link Action}(may be through parent class).<br/>
 * Url will be the package path under rootpkg.<br/>
 * <b>example</b><br/>
 * action class:
 * <p><blockquote><pre>
 *     package com.my.app.web.user;
 *     public class insert {
 *        {@code @}Action
 *         public Object act() {...}
 *     }
 * </pre></blockquote><p>
 * This action method will be mapped to url: /user/insert.act
 * @see #map(String)
 * @see Action
 * @param rootpkg action class package
 */
@SuppressWarnings("deprecation")
final protected void autoMap(String rootpkg) {
    DefaultAction.defPagePkg = rootpkg;
    try {
        Enumeration<URL> enm = getClass().getClassLoader().getResources(rootpkg.replace('.', '/'));
        while (enm.hasMoreElements()) {
            URL url = enm.nextElement();
            if (url.getProtocol().equals("file")) {
                autoMap(rootpkg.replace('.', '/'), rootpkg, new File(URLDecoder.decode(url.getFile())));
            } else if (url.getProtocol().equals("jar")) {
                String file = URLDecoder.decode(url.getFile());
                String root = file.substring(file.lastIndexOf('!') + 2);
                file = file.substring(0, file.length() - root.length() - 2);
                URL jarurl = new URL(file);
                if (jarurl.getProtocol().equals("file")) {
                    JarFile jarFile = new JarFile(URLDecoder.decode(jarurl.getFile()));
                    try {
                        Enumeration<JarEntry> entries = jarFile.entries();
                        while (entries.hasMoreElements()) {
                            JarEntry entry = entries.nextElement();
                            String name = entry.getName();
                            if (!name.endsWith(".class"))
                                continue;
                            if (!name.startsWith(root + '/'))
                                continue;
                            name = name.substring(0, name.length() - 6);
                            name = name.replace('/', '.');
                            int i = name.lastIndexOf('.');
                            autoMap(root, name.substring(0, i), name.substring(i + 1));
                        }
                    } finally {
                        jarFile.close();
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.storm.localizer.LocallyCachedTopologyBlob.java

protected void extractDirFromJar(String jarpath, String dir, Path dest) throws IOException {
    LOG.debug("EXTRACTING {} from {} and placing it at {}", dir, jarpath, dest);
    try (JarFile jarFile = new JarFile(jarpath)) {
        String toRemove = dir + '/';
        Enumeration<JarEntry> jarEnums = jarFile.entries();
        while (jarEnums.hasMoreElements()) {
            JarEntry entry = jarEnums.nextElement();
            String name = entry.getName();
            if (!entry.isDirectory() && name.startsWith(toRemove)) {
                String shortenedName = name.replace(toRemove, "");
                Path aFile = dest.resolve(shortenedName);
                LOG.debug("EXTRACTING {} SHORTENED to {} into {}", name, shortenedName, aFile);
                fsOps.forceMkdir(aFile.getParent());
                try (FileOutputStream out = new FileOutputStream(aFile.toFile());
                        InputStream in = jarFile.getInputStream(entry)) {
                    IOUtils.copy(in, out);
                }//from  ww  w .ja va2s. co m
            }
        }
    }
}

From source file:com.moss.nomad.core.packager.Packager.java

private static String[] listJarPaths(File file) throws Exception {

    JarFile jar = new JarFile(file);
    Enumeration<JarEntry> e = jar.entries();
    List<String> paths = new ArrayList<String>();

    while (e.hasMoreElements()) {
        JarEntry entry = e.nextElement();
        paths.add(entry.getName());//from w w  w. ja v  a 2 s .c o m
    }

    return paths.toArray(new String[0]);
}

From source file:de.uzk.hki.da.utils.Utilities.java

public static String getBuildNumber() {
    String buildNumber = "fakeBuildNumber";
    try {/*from  ww  w .j a va  2s  .c o  m*/
        JarFile file = null;
        Manifest mf = null;
        file = new JarFile(new File(
                Utilities.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()));
        mf = file.getManifest();
        Attributes attr = mf.getMainAttributes();
        buildNumber = attr.getValue("buildNumber");
    } catch (Exception e) {
        logger.debug("Can not extract the build number from ");
    }
    return buildNumber;
}

From source file:org.devproof.portal.core.module.theme.service.ThemeServiceImpl.java

private File createDefaultTheme(String[] themePaths, String[] filterPaths) {
    try {/*  w  w w . ja  v  a2s.  c  o  m*/
        @SuppressWarnings("unchecked")
        Set<String> libs = servletContext.getResourcePaths("/WEB-INF/lib");
        Set<String> zipResources = new HashSet<String>();
        File back = File.createTempFile("devproof-defaulttheme-", ".zip");
        FileOutputStream fos = new FileOutputStream(back);
        ZipOutputStream zos = new ZipOutputStream(fos);
        if (libs.isEmpty()) {
            // development variant
            Resource root[] = applicationContext.getResources("classpath*:/");
            for (String ext : ThemeConstants.ALLOWED_THEME_EXT) {
                for (String themePath : themePaths) {
                    final Resource resources[];
                    if (themePath.endsWith("/")) {
                        resources = applicationContext.getResources("classpath*:" + themePath + "**/*" + ext);
                    } else {
                        resources = applicationContext.getResources("classpath*:" + themePath + ext);
                    }
                    for (Resource r : resources) {
                        String zipPath = getZipPath(root, r);
                        if (zipPath != null && !isFiltered(null, filterPaths, zipPath)
                                && !zipResources.contains(zipPath)) {
                            zipResources.add(zipPath);
                            ZipEntry ze = new ZipEntry(zipPath);
                            zos.putNextEntry(ze);
                            InputStream is = r.getInputStream();
                            byte[] file = new byte[is.available()];
                            is.read(file);
                            is.close();
                            zos.write(file);
                            zos.closeEntry();
                        }
                    }
                }
            }
        } else {
            // prod variant
            for (String lib : libs) {
                URL url = servletContext.getResource(lib);
                JarFile file = new JarFile(url.getFile());
                Enumeration<JarEntry> entries = file.entries();
                while (entries.hasMoreElements()) {
                    JarEntry jarEntry = entries.nextElement();
                    if (!isFiltered(themePaths, filterPaths, jarEntry.getName())
                            && !zipResources.contains(jarEntry.getName())) {
                        zipResources.add(jarEntry.getName());
                        ZipEntry ze = new ZipEntry(jarEntry.getName());
                        InputStream is = file.getInputStream(jarEntry);
                        byte[] content = new byte[is.available()];
                        is.read(content);
                        is.close();
                        zos.putNextEntry(ze);
                        zos.write(content);
                        zos.closeEntry();
                    }
                }
            }
        }
        zos.finish();
        zos.close();
        fos.close();
        return back;
    } catch (FileNotFoundException e) {
        logger.error("Unknown: ", e);
    } catch (IOException e) {
        logger.error("Unknown: ", e);
    }
    return null;
}

From source file:com.fujitsu.dc.engine.extension.support.ExtensionJarLoader.java

/**
 * jar???JavaScript??? Set??./*from   ww w .  j a v  a 2s .c om*/
 * @param jarPaths  jar?
 * @param filter Extension
 * @return Javascript??????Java?
 * @throws IOException ?????/????
 */
@SuppressWarnings("unchecked")
private Set<Class<? extends Scriptable>> loadPrototypeClassSet(List<URL> jarPaths, ExtensionClassFilter filter)
        throws IOException, DcEngineException {
    scriptableClassSet = new HashSet<Class<? extends Scriptable>>();

    for (URL jarUrl : jarPaths) {
        JarFile jar = null;
        try {
            File jarFile = new File(jarUrl.getPath());
            if (jarFile.isDirectory()) {
                continue;
            }
            jar = new JarFile(jarFile);

            for (Enumeration<JarEntry> ent = jar.entries(); ent.hasMoreElements();) {
                JarEntry entry = ent.nextElement();
                String[] pathAndName = resolveJarEntry(entry.getName());
                if (null == pathAndName) {
                    continue;
                }
                String entryPath = pathAndName[0];
                String entryName = pathAndName[1];
                if (null == entryPath || null == entryName) {
                    continue;
                }
                //   jar??"/" ????????
                entryPath = entryPath.replaceAll("\\/", "\\.");
                // ??? JavaScript????? filter??????
                if (filter.accept(entryPath, entryName)) {
                    String className = entryPath + "." + entryName;
                    try {
                        Class<?> cl = classloader.loadClass(className);
                        if (ScriptableObject.class.isAssignableFrom(cl)
                                || Scriptable.class.isAssignableFrom(cl)) {
                            scriptableClassSet.add((Class<? extends Scriptable>) cl);
                            log.info(String.format("Info: Extension class %s is revealed to JavaScript.",
                                    className));
                            // OK.
                            continue;
                        }
                        // ScriptableObject/Scriptable????????JavaScript??????
                        log.info(String.format("Info: Extension class %s is not derived from "
                                + "ScriptableObject class or does not implment Scriptable interface. Ignored.",
                                className));
                    } catch (ClassNotFoundException e) {
                        log.warn(String.format("Warn: Extension class %s is not found in classLoader: %s",
                                className, e.getMessage()), e);
                    } catch (NoClassDefFoundError e) {
                        log.warn(String.format("Warn: Extension class %s is not found in classLoader: %s",
                                className, e.getMessage()), e);
                    } catch (Exception e) {
                        log.warn(String.format("Warn: Extension class %s cannot be loaded into classLoader: %s "
                                + "or the jar content is invalid.", className, e.getMessage()), e);
                    }
                }
            }
        } catch (RuntimeException e) {
            log.warn(String.format("Warn: Failed to handle Extension jar file %s: %s", jarUrl.toString(),
                    e.getMessage()), e);
        } catch (Exception e) {
            log.warn(String.format("Warn: Failed to handle Extension jar file %s: %s", jarUrl.toString(),
                    e.getMessage()), e);
            continue;
        } finally {
            IOUtils.closeQuietly(jar);
        }
    }
    return scriptableClassSet;
}

From source file:io.personium.engine.extension.support.ExtensionJarLoader.java

/**
 * jar???JavaScript??? Set??.//w w  w .  j  av a 2 s  .  c  om
 * @param jarPaths  jar?
 * @param filter Extension
 * @return Javascript??????Java?
 * @throws IOException ?????/????
 */
@SuppressWarnings("unchecked")
private Set<Class<? extends Scriptable>> loadPrototypeClassSet(List<URL> jarPaths, ExtensionClassFilter filter)
        throws IOException, PersoniumEngineException {
    scriptableClassSet = new HashSet<Class<? extends Scriptable>>();

    for (URL jarUrl : jarPaths) {
        JarFile jar = null;
        try {
            File jarFile = new File(jarUrl.getPath());
            if (jarFile.isDirectory()) {
                continue;
            }
            jar = new JarFile(jarFile);

            for (Enumeration<JarEntry> ent = jar.entries(); ent.hasMoreElements();) {
                JarEntry entry = ent.nextElement();
                String[] pathAndName = resolveJarEntry(entry.getName());
                if (null == pathAndName) {
                    continue;
                }
                String entryPath = pathAndName[0];
                String entryName = pathAndName[1];
                if (null == entryPath || null == entryName) {
                    continue;
                }
                //   jar??"/" ????????
                entryPath = entryPath.replaceAll("\\/", "\\.");
                // ??? JavaScript????? filter??????
                if (filter.accept(entryPath, entryName)) {
                    String className = entryPath + "." + entryName;
                    try {
                        Class<?> cl = classloader.loadClass(className);
                        if (ScriptableObject.class.isAssignableFrom(cl)
                                || Scriptable.class.isAssignableFrom(cl)) {
                            scriptableClassSet.add((Class<? extends Scriptable>) cl);
                            log.info(String.format("Info: Extension class %s is revealed to JavaScript.",
                                    className));
                            // OK.
                            continue;
                        }
                        // ScriptableObject/Scriptable????????JavaScript??????
                        log.info(String.format("Info: Extension class %s is not derived from "
                                + "ScriptableObject class or does not implment Scriptable interface. Ignored.",
                                className));
                    } catch (ClassNotFoundException e) {
                        log.warn(String.format("Warn: Extension class %s is not found in classLoader: %s",
                                className, e.getMessage()), e);
                    } catch (NoClassDefFoundError e) {
                        log.warn(String.format("Warn: Extension class %s is not found in classLoader: %s",
                                className, e.getMessage()), e);
                    } catch (Exception e) {
                        log.warn(String.format("Warn: Extension class %s cannot be loaded into classLoader: %s "
                                + "or the jar content is invalid.", className, e.getMessage()), e);
                    }
                }
            }
        } catch (RuntimeException e) {
            log.warn(String.format("Warn: Failed to handle Extension jar file %s: %s", jarUrl.toString(),
                    e.getMessage()), e);
        } catch (Exception e) {
            log.warn(String.format("Warn: Failed to handle Extension jar file %s: %s", jarUrl.toString(),
                    e.getMessage()), e);
            continue;
        } finally {
            IOUtils.closeQuietly(jar);
        }
    }
    return scriptableClassSet;
}