下面列出了java.util.jar.JarFile#getInputStream ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
/**
* 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();
}
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;
}
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() + "'.");
}
}
/**
* 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();
}
/**
* 从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;
}
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();
}
}
}
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();
}
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();
}
@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;
}
}
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;
}
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);
}
}
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;
}
}
@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");
}
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);
}
}
/**
* 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);
}
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);
}
}
}
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);
}
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();
}
}
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);
}