Java Code Examples for java.util.jar.JarFile#getInputStream()

The following examples show how to use java.util.jar.JarFile#getInputStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AutoMakeLoadHandler.java    From molicode with Apache License 2.0 6 votes vote down vote up
/**
 * 从jar file中获取 autoMake 信息
 *
 * @param autoCodeParams
 * @param jarFilePath
 * @return
 * @throws IOException
 */
private AutoMakeVo loadAutoMakeFromJarFile(AutoCodeParams autoCodeParams, File jarFilePath) throws IOException {

    JarFile jarFile = new JarFile(jarFilePath);

    JarEntry jarEntry = jarFile.getJarEntry(AUTO_CODE_XML_FILE_NAME);
    if (jarEntry == null) {
        throw new AutoCodeException("maven下载的jar包中,没有autoCode.xml配置文件!", ResultCodeEnum.FAILURE);
    }

    InputStream autoCodeXmlInputStream = jarFile.getInputStream(jarEntry);
    String autoCodeContent = IOUtils.toString(autoCodeXmlInputStream, Profiles.getInstance().getFileEncoding());
    IOUtils.closeQuietly(autoCodeXmlInputStream);
    AutoMakeVo autoMake = XmlUtils.getAutoMakeByContent(autoCodeContent);

    if (autoCodeParams.getLoadTemplateContent()) {
        ThreadLocalHolder.setJarFileToCodeContext(jarFile);
        autoMakeService.loadTemplateContent(autoMake, jarFile);
    }

    loadMavenInfo(jarFile, autoMake);
    return autoMake;
}
 
Example 2
Source File: FindNativeFiles.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
boolean isNativeClass(JarFile jar, JarEntry entry) throws IOException, ConstantPoolException {
    String name = entry.getName();
    if (name.startsWith("META-INF") || !name.endsWith(".class"))
        return false;
    //String className = name.substring(0, name.length() - 6).replace("/", ".");
    //System.err.println("check " + className);
    InputStream in = jar.getInputStream(entry);
    ClassFile cf = ClassFile.read(in);
    in.close();
    for (int i = 0; i < cf.methods.length; i++) {
        Method m = cf.methods[i];
        if (m.access_flags.is(AccessFlags.ACC_NATIVE)) {
            // System.err.println(className);
            return true;
        }
    }
    return false;
}
 
Example 3
Source File: JavaPluginLoader.java    From Nemisys with GNU General Public License v3.0 6 votes vote down vote up
@Override
public PluginDescription getPluginDescription(File file) {
    try {
        JarFile jar = new JarFile(file);
        JarEntry entry = jar.getJarEntry("nemisys.yml");
        if (entry == null) {
            entry = jar.getJarEntry("plugin.yml");
            if (entry == null) {
                return null;
            }
        }
        InputStream stream = jar.getInputStream(entry);
        return new PluginDescription(Utils.readFile(stream));
    } catch (IOException e) {
        return null;
    }
}
 
Example 4
Source File: Jar.java    From scar with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static public void setClassVersions (String inJar, String outJar, int max, int min) throws IOException {
	if (DEBUG) debug("scar", "Setting class versions for JAR: " + inJar + " -> " + outJar + ", " + max + "." + min);

	JarFile inJarFile = new JarFile(inJar);
	mkdir(parent(outJar));
	JarOutputStream outJarStream = new JarOutputStream(new FileOutputStream(outJar));
	outJarStream.setLevel(Deflater.BEST_COMPRESSION);
	for (Enumeration<JarEntry> entries = inJarFile.entries(); entries.hasMoreElements();) {
		String name = entries.nextElement().getName();
		outJarStream.putNextEntry(new JarEntry(name));
		InputStream input = inJarFile.getInputStream(inJarFile.getEntry(name));
		if (name.endsWith(".class")) input = new ClassVersionStream(input, name, max, min);
		copyStream(input, outJarStream);
		outJarStream.closeEntry();
	}
	outJarStream.close();
	inJarFile.close();
}
 
Example 5
Source File: DependencyManager.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 6 votes vote down vote up
protected static Stream<ModuleAnalyzer> findModuleXmls(File file) {
    List<ModuleAnalyzer> analyzers = new ArrayList<>();
    try {
        JarFile jar = new JarFile(file);
        Enumeration<JarEntry> entries = jar.entries();

        while (entries.hasMoreElements()) {
            JarEntry each = entries.nextElement();
            String name = each.getName();

            if (name.startsWith("modules/") && name.endsWith("module.xml")) {
                InputStream in = jar.getInputStream(each);
                analyzers.add(new ModuleAnalyzer(in));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return analyzers.stream();
}
 
Example 6
Source File: MultiIndexUpdaterTest.java    From fdroidclient with GNU General Public License v3.0 6 votes vote down vote up
protected void updateRepo(IndexUpdater updater, String indexJarPath) throws UpdateException {
    File indexJar = TestUtils.copyResourceToTempFile(indexJarPath);
    try {
        if (updater instanceof IndexV1Updater) {
            JarFile jarFile = new JarFile(indexJar);
            JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);
            InputStream indexInputStream = jarFile.getInputStream(indexEntry);
            ((IndexV1Updater) updater).processIndexV1(indexInputStream, indexEntry, null);
        } else {
            updater.processDownloadedFile(indexJar);
        }
    } catch (IOException e) {
        e.printStackTrace();
        fail();
    } finally {
        if (indexJar != null && indexJar.exists()) {
            indexJar.delete();
        }
    }
}
 
Example 7
Source File: JarModifier.java    From JReFrameworker with MIT License 6 votes vote down vote up
/**
 * Extracts a Jar file
 * 
 * @param inputJar
 * @param outputPath
 * @throws IOException
 */
public static void unjar(File inputJar, File outputPath) throws IOException {
	outputPath.mkdirs();
	JarFile jar = new JarFile(inputJar);
	Enumeration<JarEntry> jarEntries = jar.entries();
	while (jarEntries.hasMoreElements()) {
		JarEntry jarEntry = jarEntries.nextElement();
		File file = new File(outputPath.getAbsolutePath() + java.io.File.separator + jarEntry.getName());
		new File(file.getParent()).mkdirs();
		if (jarEntry.isDirectory()) {
			file.mkdir();
			continue;
		}
		InputStream is = jar.getInputStream(jarEntry);
		FileOutputStream fos = new FileOutputStream(file);
		while (is.available() > 0) {
			fos.write(is.read());
		}
		fos.close();
		is.close();
	}
	jar.close();
}
 
Example 8
Source File: PackagedProgram.java    From flink with Apache License 2.0 6 votes vote down vote up
private static File copyLibToTempFile(String name, Random rnd, JarFile jar, JarEntry input, byte[] buffer) throws ProgramInvocationException {
	final File output = createTempFile(rnd, input, name);
	try (
			final OutputStream out = new FileOutputStream(output);
			final InputStream in = new BufferedInputStream(jar.getInputStream(input))
	) {
		int numRead = 0;
		while ((numRead = in.read(buffer)) != -1) {
			out.write(buffer, 0, numRead);
		}
		return output;
	} catch (IOException e) {
		throw new ProgramInvocationException("An I/O error occurred while extracting nested library '"
				+ input.getName() + "' to temporary file '" + output.getAbsolutePath() + "'.");
	}
}
 
Example 9
Source File: NarUnpacker.java    From nifi-minifi with Apache License 2.0 6 votes vote down vote up
private static List<String> determineDocumentedNiFiComponents(final JarFile jarFile,
                                                              final JarEntry jarEntry) throws IOException {
    final List<String> componentNames = new ArrayList<>();

    if (jarEntry == null) {
        return componentNames;
    }

    try (final InputStream entryInputStream = jarFile.getInputStream(jarEntry);
         final BufferedReader reader = new BufferedReader(new InputStreamReader(
                 entryInputStream))) {
        String line;
        while ((line = reader.readLine()) != null) {
            final String trimmedLine = line.trim();
            if (!trimmedLine.isEmpty() && !trimmedLine.startsWith("#")) {
                final int indexOfPound = trimmedLine.indexOf("#");
                final String effectiveLine = (indexOfPound > 0) ? trimmedLine.substring(0,
                        indexOfPound) : trimmedLine;
                componentNames.add(effectiveLine);
            }
        }
    }

    return componentNames;
}
 
Example 10
Source File: JarModifier.java    From JReFrameworker with MIT License 6 votes vote down vote up
/**
 * Extracts a Jar file
 * 
 * @param inputJar
 * @param outputPath
 * @throws IOException
 */
public static void unjar(File inputJar, File outputPath) throws IOException {
	outputPath.mkdirs();
	JarFile jar = new JarFile(inputJar);
	Enumeration<JarEntry> jarEntries = jar.entries();
	while (jarEntries.hasMoreElements()) {
		JarEntry jarEntry = jarEntries.nextElement();
		File file = new File(outputPath.getAbsolutePath() + java.io.File.separator + jarEntry.getName());
		new File(file.getParent()).mkdirs();
		if (jarEntry.isDirectory()) {
			file.mkdir();
			continue;
		}
		InputStream is = jar.getInputStream(jarEntry);
		FileOutputStream fos = new FileOutputStream(file);
		while (is.available() > 0) {
			fos.write(is.read());
		}
		fos.close();
		is.close();
	}
	jar.close();
}
 
Example 11
Source File: ClazzReplacer.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleClazz(JarFile jarFile, JarOutputStream jos, JarEntry ze, String pathName) {

    //            logger.log(pathName);
    if (reMapping.containsKey(pathName.substring(0, pathName.length() - 6))) {
        logger.info("[ClazzReplacer] remove class  " + pathName + " form " + jarFile);
        return;
    }

    try {
        InputStream in = jarFile.getInputStream(ze);
        ClassReader cr = new ClassReader(in);
        ClassWriter cw = new ClassWriter(0);
        RemappingClassAdapter remappingClassAdapter = new RemappingClassAdapter(cw, new SimpleRemapper(reMapping));
        cr.accept(remappingClassAdapter, ClassReader.EXPAND_FRAMES);

        InputStream inputStream = new ByteArrayInputStream(cw.toByteArray());
        copyStreamToJar(inputStream, jos, pathName, ze.getTime());

    } catch (Throwable e) {

        System.err.println("[ClazzReplacer] rewrite error > " + pathName);
        justCopy(jarFile, jos, ze, pathName);
    }

}
 
Example 12
Source File: RefVerifier.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
public void verifyJarFile(String jarFileName) throws IOException {
	JarFile jarFile = new JarFile(jarFileName);

	int count = classes.size();
	if (count > 0) {
		listener.verifyPathStarted("Verifying " + count + (count == 1?" class":" classes"));
	}
	classLoader.setClassPath(classPathArray);

	for (String name : classes) {
		JarEntry entry = jarFile.getJarEntry(name);
		InputStream is = jarFile.getInputStream(entry);
		verifyClass(is);
	}
}
 
Example 13
Source File: IndexV1UpdaterTest.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = IndexUpdater.UpdateException.class)
public void testIndexV1WithOldTimestamp() throws IOException, IndexUpdater.UpdateException {
    Repo repo = MultiIndexUpdaterTest.createRepo("Testy", TESTY_JAR, context, TESTY_CERT);
    repo.timestamp = System.currentTimeMillis() / 1000;
    IndexV1Updater updater = new IndexV1Updater(context, repo);
    JarFile jarFile = new JarFile(TestUtils.copyResourceToTempFile(TESTY_JAR), true);
    JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);
    InputStream indexInputStream = jarFile.getInputStream(indexEntry);
    updater.processIndexV1(indexInputStream, indexEntry, "fakeEtag");
    fail(); // it should never reach here, it should throw a SigningException
    getClass().getResourceAsStream("foo");
}
 
Example 14
Source File: AutoupdateInfoParser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Create the equivalent of {@code Info/info.xml} for an OSGi bundle.
 *
 * @param jar a bundle
 * @return a {@code <module ...><manifest .../></module>} valid according to
 * <a href="http://www.netbeans.org/dtds/autoupdate-info-2_5.dtd">DTD</a>
 */
private static Element fakeOSGiInfoXml(JarFile jar, File whereFrom) throws IOException {
    java.util.jar.Attributes attr = jar.getManifest().getMainAttributes();
    Properties localized = new Properties();
    String bundleLocalization = attr.getValue("Bundle-Localization");
    if (bundleLocalization != null) {
        InputStream is = jar.getInputStream(jar.getEntry(bundleLocalization + ".properties"));
        try {
            localized.load(is);
        } finally {
            is.close();
        }
    }
    return fakeOSGiInfoXml(attr, localized, whereFrom);
}
 
Example 15
Source File: JarContentsManager.java    From flow with Apache License 2.0 5 votes vote down vote up
private byte[] getJarEntryContents(JarFile jarFile, JarEntry entry) {
    if (entry == null) {
        return null;
    }

    try (InputStream entryStream = jarFile.getInputStream(entry)) {
        return IOUtils.toByteArray(entryStream);
    } catch (IOException e) {
        throw new UncheckedIOException(String.format(
                "Failed to get entry '%s' contents from jar file '%s'",
                entry, jarFile), e);
    }
}
 
Example 16
Source File: NativeLoader.java    From opsu-dance with GNU General Public License v3.0 5 votes vote down vote up
private static void unpack(JarFile jarfile, File destination, String filename)
	throws IOException
{
	try (
		InputStream in = jarfile.getInputStream(jarfile.getEntry(filename));
		OutputStream out = new FileOutputStream(destination))
	{
		byte[] buffer = new byte[65536];
		int bufferSize;
		while ((bufferSize = in.read(buffer, 0, buffer.length)) != -1) {
			out.write(buffer, 0, bufferSize);
		}
	}
}
 
Example 17
Source File: MakeUpdateDesc.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Element fakeOSGiInfoXml(JarFile jar, File whereFrom, Document doc) throws IOException {
    Attributes attr = jar.getManifest().getMainAttributes();
    Properties localized = new Properties();
    String bundleLocalization = attr.getValue("Bundle-Localization");
    if (bundleLocalization != null) {
        try (InputStream is = jar.getInputStream(jar.getEntry(bundleLocalization + ".properties"))) {
            localized.load(is);
        }
    }
    return fakeOSGiInfoXml(attr, localized, whereFrom, doc);
}
 
Example 18
Source File: ClassFileReader.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
protected ClassFile readClassFile(JarFile jarfile, JarEntry e) throws IOException {
    InputStream is = null;
    try {
        is = jarfile.getInputStream(e);
        return ClassFile.read(is);
    } catch (ConstantPoolException ex) {
        throw new ClassFileError(ex);
    } finally {
        if (is != null)
            is.close();
    }
}
 
Example 19
Source File: Devices.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public static DeviceEntry getDevice(String device) {
	try {
		if (device==null) return null;
		if (devices.containsKey(device))
			return (DeviceEntry)devices.get(device);
		else {
			File f = new File(OS.getFolderMyDevices()+File.separator+device+".ftd");
			if (f.exists()) {
				DeviceEntry ent=null;
				JarFile jar = new JarFile(f);
				Enumeration e = jar.entries();
		    	while (e.hasMoreElements()) {
		    	    JarEntry file = (JarEntry) e.nextElement();
		    	    if (file.getName().endsWith(device+".properties")) {
			    	    InputStream is = jar.getInputStream(file); // get the input stream
			    	    PropertiesFile p = new PropertiesFile();
			    	    p.load(is);
			    	    ent = new DeviceEntry(p);
		    	    }
		    	}
		    	return ent;
			}
			else return null;
		}
	}
	catch (Exception ex) {
		ex.printStackTrace();
		return null;
	}
}
 
Example 20
Source File: TestVectorRunner.java    From aws-encryption-sdk-java with Apache License 2.0 4 votes vote down vote up
private static InputStream readFromJar(JarFile jar, String name) throws IOException {
    // Our manifest URIs incorrectly start with file:// rather than just file: so we need to strip this
    ZipEntry entry = jar.getEntry(name.replaceFirst("^file://(?!/)", ""));
    return jar.getInputStream(entry);
}