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:org.eclipse.ecr.testlib.NXRuntimeTestCase.java

protected void initUrls() throws Exception {
    ClassLoader classLoader = NXRuntimeTestCase.class.getClassLoader();
    if (classLoader instanceof URLClassLoader) {
        urls = ((URLClassLoader) classLoader).getURLs();
    } else if (classLoader.getClass().getName().equals("org.apache.tools.ant.AntClassLoader")) {
        Method method = classLoader.getClass().getMethod("getClasspath");
        String cp = (String) method.invoke(classLoader);
        String[] paths = cp.split(File.pathSeparator);
        urls = new URL[paths.length];
        for (int i = 0; i < paths.length; i++) {
            urls[i] = new URL("file:" + paths[i]);
        }/*w  w  w. j  av  a2 s.  co  m*/
    } else {
        log.warn("Unknow classloader type: " + classLoader.getClass().getName()
                + "\nWon't be able to load OSGI bundles");
        return;
    }
    // special case for maven surefire with useManifestOnlyJar
    if (urls.length == 1) {
        try {
            URI uri = urls[0].toURI();
            if (uri.getScheme().equals("file") && uri.getPath().contains("surefirebooter")) {
                JarFile jar = new JarFile(new File(uri));
                try {
                    String cp = jar.getManifest().getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
                    if (cp != null) {
                        String[] cpe = cp.split(" ");
                        URL[] newUrls = new URL[cpe.length];
                        for (int i = 0; i < cpe.length; i++) {
                            // Don't need to add 'file:' with maven surefire
                            // >= 2.4.2
                            String newUrl = cpe[i].startsWith("file:") ? cpe[i] : "file:" + cpe[i];
                            newUrls[i] = new URL(newUrl);
                        }
                        urls = newUrls;
                    }
                } finally {
                    jar.close();
                }
            }
        } catch (Exception e) {
            // skip
        }
    }
    StringBuilder sb = new StringBuilder();
    sb.append("URLs on the classpath: ");
    for (URL url : urls) {
        sb.append(url.toString());
        sb.append('\n');
    }
    log.debug(sb.toString());
    readUris = new HashSet<URI>();
    bundles = new HashMap<String, BundleFile>();
}

From source file:com.kotcrab.vis.editor.module.editor.PluginLoaderModule.java

private void loadPluginsJars() throws IOException {
    Array<URL> urls = new Array<>();

    for (PluginDescriptor descriptor : pluginsToLoad) {
        for (FileHandle lib : descriptor.libs)
            urls.add(new URL("jar:file:" + lib.path() + "!/"));

        urls.add(new URL("jar:file:" + descriptor.file.path() + "!/"));
    }/*from w  w  w.j  a v a  2  s  .  c om*/

    URLClassLoader classLoader = ChildFirstURLClassLoader.newInstance(urls.toArray(URL.class),
            Thread.currentThread().getContextClassLoader());
    Thread.currentThread().setContextClassLoader(classLoader);

    for (PluginDescriptor descriptor : pluginsToLoad) {
        try {
            if (descriptor.compatibility != App.PLUGIN_COMPATIBILITY_CODE)
                Log.warn(TAG, "Loading: " + descriptor.folderName
                        + " (compatibility code mismatch! Will try to load anyway!)");
            else
                Log.debug(TAG, "Loading: " + descriptor.folderName);

            currentlyLoadingPlugin = descriptor.folderName;

            JarFile jarFile = new JarFile(descriptor.file.path());
            loadJarClasses(classLoader, descriptor, jarFile.entries());
            IOUtils.closeQuietly(jarFile);
        } catch (IOException | ReflectiveOperationException | LinkageError e) {
            loadingCurrentPluginFailed(e);
        }
    }
}

From source file:org.ebayopensource.turmeric.plugins.maven.resources.ResourceLocator.java

private URI findFileResource(File path, String pathref) {
    if (path.isFile()) {
        // Assume its an archive.
        String extn = FilenameUtils.getExtension(path.getName());
        if (StringUtils.isBlank(extn)) {
            log.debug("No extension found for file: " + path);
            return null;
        }//  www. j  a v  a  2s.c o  m

        extn = extn.toLowerCase();
        if ("jar".equals(extn)) {
            log.debug("looking inside of jar file: " + path);
            JarFile jar = null;
            try {
                jar = new JarFile(path);
                JarEntry entry = jar.getJarEntry(pathref);
                if (entry == null) {
                    log.debug("JarEntry not found: " + pathref);
                    return null;
                }

                String uripath = String.format("jar:%s!/%s", path.toURI(), entry.getName());
                try {
                    return new URI(uripath);
                } catch (URISyntaxException e) {
                    log.debug("Unable to create URI reference: " + path, e);
                    return null;
                }
            } catch (JarException e) {
                log.debug("Unable to open archive: " + path, e);
                return null;
            } catch (IOException e) {
                log.debug("Unable to open archive: " + path, e);
                return null;
            } finally {
                if (jar != null) {
                    try {
                        jar.close();
                    } catch (IOException e) {
                        log.debug("Unable to close jar: " + path, e);
                    }
                }
            }
        }

        log.debug("Unsupported archive file: " + path);
        return null;
    }

    if (path.isDirectory()) {
        File testFile = new File(path, FilenameUtils.separatorsToSystem(pathref));
        if (testFile.exists() && testFile.isFile()) {
            return testFile.toURI();
        }

        log.debug("Not found in directory: " + testFile);
        return null;
    }

    log.debug("Unable to handle non-file, non-directory " + File.class.getName() + " objects: " + path);
    return null;
}

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

private boolean recognizeTISJob(File entity) {
    boolean isTISEntry = false;
    List<File> checkList = new ArrayList<File>();
    JoboxUtil.findFirstFile(null, entity, "classpath.jar", checkList); //$NON-NLS-1$
    if (checkList.size() > 0) {
        try {/*from   www . j a  v a  2 s  .c  o  m*/
            JarFile jarFile = new JarFile(checkList.get(0).getAbsolutePath());
            Manifest jarFileManifest = jarFile.getManifest();
            String vendorInfo = jarFileManifest.getMainAttributes().getValue("Implementation-Vendor"); //$NON-NLS-1$
            if (vendorInfo.trim().toUpperCase().startsWith("TALEND")) //$NON-NLS-1$
                isTISEntry = true;
        } catch (IOException e) {
            throw new JoboxException(e);
        }
    }
    return isTISEntry;
}

From source file:com.opengamma.web.WebAbout.java

private static Set<URL> forManifest(final URL url) {
    Set<URL> result = Sets.newLinkedHashSet();
    result.add(url);//  w  w w .  j  av a2  s.c  om
    try {
        final String part = ClasspathHelper.cleanPath(url);
        File jarFile = new File(part);
        try (JarFile myJar = new JarFile(part)) {
            URL validUrl = tryToGetValidUrl(jarFile.getPath(), new File(part).getParent(), part);
            if (validUrl != null) {
                result.add(validUrl);
            }
            final Manifest manifest = myJar.getManifest();
            if (manifest != null) {
                final String classPath = manifest.getMainAttributes()
                        .getValue(new Attributes.Name("Class-Path"));
                if (classPath != null) {
                    for (String jar : classPath.split(" ")) {
                        validUrl = tryToGetValidUrl(jarFile.getPath(), new File(part).getParent(), jar);
                        if (validUrl != null) {
                            result.add(validUrl);
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        // don't do anything, we're going on the assumption it is a jar, which could be wrong
    }
    return result;
}

From source file:org.eclipse.jdt.ls.core.internal.codemanipulation.ImportOrganizeTest.java

private void addFilesFromJar(IJavaProject javaProject, File jarFile, String encoding)
        throws InvocationTargetException, CoreException, IOException {
    IFolder src = (IFolder) fSourceFolder.getResource();
    File targetFile = src.getLocation().toFile();
    try (JarFile file = new JarFile(jarFile)) {
        for (JarEntry entry : Collections.list(file.entries())) {
            if (entry.isDirectory()) {
                continue;
            }//from  w w w. j a v a2s. c o  m
            try (InputStream in = file.getInputStream(entry);
                    Reader reader = new InputStreamReader(in, encoding)) {
                File outFile = new File(targetFile, entry.getName());
                outFile.getParentFile().mkdirs();
                try (OutputStream out = new FileOutputStream(outFile);
                        Writer writer = new OutputStreamWriter(out, encoding)) {
                    IOUtils.copy(reader, writer);
                }
            }
        }
    }
    javaProject.getProject().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
}

From source file:org.obiba.onyx.spring.AnnotatedBeanFinderFactoryBean.java

/**
 * @param res//from w  w  w  .  j  a v a2 s.c o m
 * @throws Exception
 */
private void dealWithJars(Resource res) throws Exception {
    // Enumerate all entries in this JAR file.
    Enumeration<JarEntry> jarEntries = new JarFile(res.getFile()).entries();
    while (jarEntries.hasMoreElements()) {
        String name = jarEntries.nextElement().getName();

        // If the entry is a class, deal with it.
        if (name.endsWith(".class") && !name.equals("")) {
            // Format the path first.
            name = pathToQualifiedClassName(name);

            // Apply the qualified class name pattern to improve the
            // searching performance.
            if (matchQualifiedClassNamePatterns(name))
                // This is the qualified class name, so add it.
                addPossibleClasses(name);
        }
    }
}

From source file:com.zb.jcseg.core.JcsegTaskConfig.java

/**
 * reset the value of its options from a propertie file . <br />
 * /*w w w  . j  a v a  2s  .  c  om*/
 * @param proFile path of jcseg.properties file. when null is givend, jcseg will look up the default
 * jcseg.properties file. <br />
 * @throws IOException
 */
public void resetFromPropertyFile(String proFile) throws IOException {
    Properties lexPro = new Properties();
    String jarPath = null;
    /* load the mapping from the default property file. */
    if (proFile == null) {
        /**
         * <pre>
         *      0.load the jcseg.properties from the current data.
         *      1.load the jcseg.properties located with the jar file. 
         *      2.load the jcseg.properties from the classpath. 
         *      3.load the jcseg.properties from the user.home.
         * </pre>
         */
        boolean jcseg_properties = false;
        File pro_file = null;
        String fileName = System.getProperty("jcseg.properties.path");
        if (StringUtils.isNotEmpty(fileName)) {
            pro_file = new File(fileName);
            if (pro_file.exists()) {
                lexPro.load(new FileReader(pro_file));
                jcseg_properties = true;
            }
        }

        // File pro_file = stream2file(this.getClass().getResourceAsStream("/data/" + LEX_PROPERTY_FILE));
        // File pro_file = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile());
        // InputStream in = getClass().getResourceAsStream("/data/" + LEX_PROPERTY_FILE);

        if (!jcseg_properties) {
            lexPro.load(this.getClass().getResourceAsStream("/data/" + LEX_PROPERTY_FILE));
            if (!lexPro.isEmpty()) {
                jcseg_properties = true;
                jarPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
                logger.info("resetFromPropertyFile jarPath :" + jarPath);
                // URL jarUrl = new URL(jarPath);
                // JarURLConnection jarCon = (JarURLConnection) jarUrl.openConnection();
                // jarCon.getJarFile();
                jarPath = StringUtils.remove(jarPath, ".jar");
                File workDir = new File(jarPath);
                // File.createTempFile("", "", new File(StringUtils.remove(jarPath, ".jar")));
                workDir.delete();
                workDir.mkdirs();
                if (!workDir.isDirectory()) {
                    logger.info("Mkdirs failed to create " + workDir);
                    throw new IOException("Mkdirs failed to create " + workDir);
                }
                logger.info("resetFromPropertyFile workDir :" + workDir.getPath());
                unJar(new JarFile(jarPath + ".jar"), workDir);
            }
        }
        if (!jcseg_properties) {
            pro_file = new File(JAR_HOME + "/" + LEX_PROPERTY_FILE);
            if (pro_file.exists()) {
                lexPro.load(new FileReader(pro_file));
                jcseg_properties = true;
            }
        }
        if (!jcseg_properties) {
            InputStream is = JcsegDictionaryFactory.class.getResourceAsStream("/" + LEX_PROPERTY_FILE);
            if (is != null) {
                lexPro.load(new BufferedInputStream(is));
                jcseg_properties = true;
            }
        }
        if (!jcseg_properties) {
            pro_file = new File(System.getProperty("user.home") + "/" + LEX_PROPERTY_FILE);
            if (pro_file.exists()) {
                lexPro.load(new FileReader(pro_file));
                jcseg_properties = true;
            }
        }

        /*
         * jcseg properties file loading status report, show the crorrent properties file location information . <br
         * />
         * @date 2014-09-06
         */
        if (!jcseg_properties) {
            String _report = "jcseg properties[jcseg.properties] file loading error: \n";
            _report += "try the follwing ways to solve the problem: \n";
            _report += "1. put jcseg.properties into the classpath.\n";
            _report += "2. put jcseg.properties together with the jcseg-core-{version}.jar file.\n";
            _report += "3. put jcseg.properties in directory " + System.getProperty("user.home") + "\n\n";
            throw new IOException(_report);
        }
    }
    /* load the mapping from the specified property file. */
    else {
        File pro_file = new File(proFile);
        if (!pro_file.exists())
            throw new IOException("property file [" + proFile + "] not found!");
        lexPro.load(new FileReader(pro_file));
    }

    /* about the lexicon */
    // the lexicon path
    logger.info("jcseg.properties :" + lexPro.values());
    lexPath = (StringUtils.isNotEmpty(jarPath) ? jarPath : StringUtils.EMPTY)
            + lexPro.getProperty("lexicon.path");
    logger.info("################ jarPath : " + jarPath);
    logger.info("################ jcseg.properties lexicon.path : " + lexPro.getProperty("lexicon.path"));
    logger.info("################ lexPath : " + lexPath);
    // lexPath = this.getClass().getResource(lexPath).getFile();
    if (lexPath == null) {
        throw new IOException("lexicon.path property not find in jcseg.properties file!!!");
    }
    if (lexPath.indexOf("{jar.dir}") > -1)
        lexPath = lexPath.replace("{jar.dir}", JAR_HOME);
    // System.out.println("path: "+lexPath);

    // the lexicon file prefix and suffix
    if (lexPro.getProperty("lexicon.suffix") != null)
        suffix = lexPro.getProperty("lexicon.suffix");
    if (lexPro.getProperty("lexicon.prefix") != null)
        prefix = lexPro.getProperty("lexicon.prefix");

    // reset all the options
    if (lexPro.getProperty("jcseg.maxlen") != null)
        MAX_LENGTH = Integer.parseInt(lexPro.getProperty("jcseg.maxlen"));
    if (lexPro.getProperty("jcseg.mixcnlen") != null)
        MIX_CN_LENGTH = Integer.parseInt(lexPro.getProperty("jcseg.mixcnlen"));
    if (lexPro.getProperty("jcseg.icnname") != null && lexPro.getProperty("jcseg.icnname").equals("1"))
        I_CN_NAME = true;
    if (lexPro.getProperty("jcseg.cnmaxlnadron") != null)
        MAX_CN_LNADRON = Integer.parseInt(lexPro.getProperty("jcseg.cnmaxlnadron"));
    if (lexPro.getProperty("jcseg.nsthreshold") != null)
        NAME_SINGLE_THRESHOLD = Integer.parseInt(lexPro.getProperty("jcseg.nsthreshold"));
    if (lexPro.getProperty("jcseg.pptmaxlen") != null)
        PPT_MAX_LENGTH = Integer.parseInt(lexPro.getProperty("jcseg.pptmaxlen"));
    if (lexPro.getProperty("jcseg.loadpinyin") != null && lexPro.getProperty("jcseg.loadpinyin").equals("1"))
        LOAD_CJK_PINYIN = true;
    if (lexPro.getProperty("jcseg.loadsyn") != null && lexPro.getProperty("jcseg.loadsyn").equals("1"))
        LOAD_CJK_SYN = true;
    if (lexPro.getProperty("jcseg.loadpos") != null && lexPro.getProperty("jcseg.loadpos").equals("1"))
        LOAD_CJK_POS = true;
    if (lexPro.getProperty("jcseg.clearstopword") != null
            && lexPro.getProperty("jcseg.clearstopword").equals("1"))
        CLEAR_STOPWORD = true;
    if (lexPro.getProperty("jcseg.cnnumtoarabic") != null
            && lexPro.getProperty("jcseg.cnnumtoarabic").equals("0"))
        CNNUM_TO_ARABIC = false;
    if (lexPro.getProperty("jcseg.cnfratoarabic") != null
            && lexPro.getProperty("jcseg.cnfratoarabic").equals("0"))
        CNFRA_TO_ARABIC = false;
    if (lexPro.getProperty("jcseg.keepunregword") != null
            && lexPro.getProperty("jcseg.keepunregword").equals("1"))
        KEEP_UNREG_WORDS = true;
    if (lexPro.getProperty("lexicon.autoload") != null && lexPro.getProperty("lexicon.autoload").equals("1"))
        lexAutoload = true;
    if (lexPro.getProperty("lexicon.polltime") != null)
        polltime = Integer.parseInt(lexPro.getProperty("lexicon.polltime"));
    if (lexPro.getProperty("wiselyUnionWord") != null && lexPro.getProperty("wiselyUnionWord").equals("1"))
        wiselyUnionWord = true;

    // secondary split
    if (lexPro.getProperty("jcseg.ensencondseg") != null
            && lexPro.getProperty("jcseg.ensencondseg").equals("0"))
        EN_SECOND_SEG = false;
    if (lexPro.getProperty("jcseg.stokenminlen") != null)
        STOKEN_MIN_LEN = Integer.parseInt(lexPro.getProperty("jcseg.stokenminlen"));

    // load the keep punctuations.
    if (lexPro.getProperty("jcseg.keeppunctuations") != null)
        KEEP_PUNCTUATIONS = lexPro.getProperty("jcseg.keeppunctuations");
}

From source file:com.flagleader.builder.BuilderConfig.java

public static void jarExtracting(String paramString1, String paramString2) {
    int i1 = 2048;
    BufferedOutputStream localBufferedOutputStream = null;
    BufferedInputStream localBufferedInputStream = null;
    JarEntry localJarEntry = null;
    JarFile localJarFile = null;//from w ww  .  j a  va  2  s  .c  o  m
    Enumeration localEnumeration = null;
    try {
        localJarFile = new JarFile(paramString2);
        localEnumeration = localJarFile.entries();
        while (localEnumeration.hasMoreElements()) {
            localJarEntry = (JarEntry) localEnumeration.nextElement();
            if (localJarEntry.isDirectory()) {
                new File(paramString1 + localJarEntry.getName()).mkdirs();
            } else {
                localBufferedInputStream = new BufferedInputStream(localJarFile.getInputStream(localJarEntry));
                byte[] arrayOfByte = new byte[i1];
                FileOutputStream localFileOutputStream = new FileOutputStream(
                        paramString1 + localJarEntry.getName());
                localBufferedOutputStream = new BufferedOutputStream(localFileOutputStream, i1);
                int i2;
                while ((i2 = localBufferedInputStream.read(arrayOfByte, 0, i1)) != -1)
                    localBufferedOutputStream.write(arrayOfByte, 0, i2);
                localBufferedOutputStream.flush();
                localBufferedOutputStream.close();
                localBufferedInputStream.close();
            }
        }
    } catch (Exception localException1) {
        localException1.printStackTrace();
        try {
            if (localBufferedOutputStream != null) {
                localBufferedOutputStream.flush();
                localBufferedOutputStream.close();
            }
            if (localBufferedInputStream != null)
                localBufferedInputStream.close();
        } catch (Exception localException2) {
            localException2.printStackTrace();
        }
    } finally {
        try {
            if (localBufferedOutputStream != null) {
                localBufferedOutputStream.flush();
                localBufferedOutputStream.close();
            }
            if (localBufferedInputStream != null)
                localBufferedInputStream.close();
        } catch (Exception localException3) {
            localException3.printStackTrace();
        }
    }
}

From source file:org.jahia.modules.modulemanager.flow.ModuleManagementFlowHandler.java

private void installBundles(File file, MessageContext context, String originalFilename, boolean forceUpdate,
        boolean autoStart) throws IOException, BundleException {

    JarFile jarFile = new JarFile(file);
    try {/* w w  w .  ja  v a 2  s.com*/

        Attributes manifestAttributes = jarFile.getManifest().getMainAttributes();
        String jahiaRequiredVersion = manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_REQUIRED_VERSION);
        if (StringUtils.isEmpty(jahiaRequiredVersion)) {
            context.addMessage(new MessageBuilder().source("moduleFile")
                    .code("serverSettings.manageModules.install.required.version.missing.error").error()
                    .build());
            return;
        }
        if (new Version(jahiaRequiredVersion).compareTo(new Version(Jahia.VERSION)) > 0) {
            context.addMessage(new MessageBuilder().source("moduleFile")
                    .code("serverSettings.manageModules.install.required.version.error")
                    .args(jahiaRequiredVersion, Jahia.VERSION).error().build());
            return;
        }

        if (manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_NAME) != null) {
            handlePackage(jarFile, manifestAttributes, originalFilename, forceUpdate, autoStart, context);
        } else {
            ModuleInstallationResult installationResult = installModule(file, context, null, null, forceUpdate,
                    autoStart);
            if (installationResult != null) {
                addModuleInstallationMessage(installationResult, context);
            }
        }
    } finally {
        jarFile.close();
    }
}