下面列出了java.util.jar.JarInputStream#getNextJarEntry ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public MTSClassLoader(InputStream stream, URL[] urls, ClassLoader parent) throws IOException
{
super(urls, null);
this.parent = parent;
JarInputStream is = new JarInputStream(stream);
JarEntry entry = is.getNextJarEntry();
while (entry != null) {
if (entry.getName().contains(".class")) {
String className = entry.getName().replace(".class", "").replace('/', '.');
byte[] classBytes = bufferStream(is);
classes.put(className, classBytes);
}
entry = is.getNextJarEntry();
}
}
static void copyJarFile(JarInputStream in, JarOutputStream out) throws IOException {
if (in.getManifest() != null) {
ZipEntry me = new ZipEntry(JarFile.MANIFEST_NAME);
out.putNextEntry(me);
in.getManifest().write(out);
out.closeEntry();
}
byte[] buffer = new byte[1 << 14];
for (JarEntry je; (je = in.getNextJarEntry()) != null; ) {
out.putNextEntry(je);
for (int nr; 0 < (nr = in.read(buffer)); ) {
out.write(buffer, 0, nr);
}
}
in.close();
markJarFile(out); // add PACK200 comment
}
private static Map<String, ClassCode> loadJar(JarInputStream jarInputStream) {
Map<String, ClassCode> map = new HashMap<>(100);
try {
JarEntry jarEntry;
while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
if (!jarEntry.isDirectory() && jarEntry.getName().endsWith(Constants.CLASS_SUFFIX)) {
byte[] bytes = IOUtils.toByteArray(jarInputStream);
ClassCode classCode = load(bytes);
map.put(classCode.name, classCode);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return map;
}
/**
* Reads JAR file and stored classes locally.
*
* @param fileName Name of file to read.
* @throws IOException If read failed.
*/
private void readJarFile(String fileName) throws IOException {
JarEntry je;
JarInputStream jis = new JarInputStream(new FileInputStream(fileName));
while ((je = jis.getNextJarEntry()) != null) {
String jarName = je.getName();
if (jarName.endsWith(".class"))
loadClassBytes(jis, jarName);
// Else ignore it; it could be an image or audio file.
jis.closeEntry();
}
}
private static Map<String, ClassCode> loadJar(JarInputStream jarInputStream) {
Map<String, ClassCode> map = new HashMap<>(100);
try (jarInputStream) {
JarEntry jarEntry;
while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
if (!jarEntry.isDirectory() && jarEntry.getName().endsWith(Constants.CLASS_SUFFIX)) {
byte[] bytes = IOUtils.toByteArray(jarInputStream);
ClassCode classCode = load(bytes);
map.put(classCode.name, classCode);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return map;
}
/**
* 从jar包输入流解压需要的文件到目标目录
*
* @param inputStream jar包输入流
* @param dir 目标目录
* @param dep 是否是Spring Boot依赖包的解压, 只有为false时
* @throws IOException 出现IO错误
*/
private void extraJarStream(InputStream inputStream, String dir, boolean dep, boolean jarInit) throws IOException {
JarEntry entry = null;
JarInputStream jarInputStream = new JarInputStream(inputStream);
while ((entry = jarInputStream.getNextJarEntry()) != null) {
String name = entry.getName();
if (((name.endsWith(SUFFIX_GROOVY)
|| name.endsWith(SUFFIX_XML)
|| name.endsWith(SUFFIX_XLSX)
|| name.endsWith(SUFFIX_SQL)) && name.contains(PREFIX_SCRIPT_DB))) {
if (name.startsWith(PREFIX_SPRING_BOOT_CLASSES)) {
name = name.substring(PREFIX_SPRING_BOOT_CLASSES.length());
}
File file = new File(dir + name);
if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
throw new IOException("create dir fail: " + file.getParentFile().getAbsolutePath());
}
try (FileOutputStream outputStream = new FileOutputStream(file)) {
StreamUtils.copy(jarInputStream, outputStream);
}
} else if (name.endsWith(SUFFIX_JAR) && jarInit) {
extraJarStream(jarInputStream, dir, true, true);
}
}
}
/**
* List the names of the entries in the given {@link JarInputStream} that begin with the
* specified {@code path}. Entries will match with or without a leading slash.
*
* @param jar The JAR input stream
* @param path The leading path to match
* @return The names of all the matching entries
* @throws IOException If I/O errors occur
*/
private List<String> listResources(JarInputStream jar, String path) throws IOException {
// Include the leading and trailing slash when matching names
if (!path.startsWith(PATH_SP)) {
path = PATH_SP + path;
}
if (!path.endsWith(PATH_SP)) {
path = path + PATH_SP;
}
// Iterate over the entries and collect those that begin with the requested path
List<String> resources = new ArrayList<String>();
for (JarEntry entry; (entry = jar.getNextJarEntry()) != null;) {
if (!entry.isDirectory()) {
// Add leading slash if it's missing
String name = entry.getName();
StringBuilder sb = new StringBuilder("");
if (!name.startsWith(PATH_SP)) {
name = sb.append(PATH_SP).append(name).toString();
}
// Check file name
if (name.startsWith(path)) {
// Trim leading slash
resources.add(name.substring(1));
}
}
}
return resources;
}
private void assertMethodParameters(
final File jar, final boolean expected
) throws Exception {
final Boolean unexpectedValue = expected ? Boolean.FALSE : Boolean.TRUE;
String unexpected = null;
final JarInputStream jis = new JarInputStream(new FileInputStream(jar));
try {
for (JarEntry entry = jis.getNextJarEntry();
entry != null && unexpected == null;
entry = jis.getNextJarEntry()) {
if (!entry.isDirectory() &&
entry.getName().toLowerCase().endsWith(".class")) {
final Map<String, Boolean> result = new LinkedHashMap<String, Boolean>();
new ClassReader(jis).accept(new MethodParameterVisitor(result), 0);
unexpected = getKeyFor(result, unexpectedValue);
}
}
} finally {
try {
jis.close();
} catch (Exception ex) {
// ignore
}
}
if (unexpected != null) {
assertEquals(
(expected ? "Missing " : "Unexpected ") +
"MethodParameters attribute for " + unexpected,
expected,
!expected);
}
}
/**
* Compares the entries in the given 2 aar files and the entries in "classes.jar" in them.
* However, this function does not compare the contents of the entries themselves.
*
* @param aarFile1 Path to the first aar file.
* @param aarFile2 Path to the second aar file.
* @return True iff the entries present in the two aar files are the same and entries in
* "classes.jar" in the two aar files are the same.
* @throws IOException if an error happens when reading aar files.
*/
public static boolean compareEntriesInAars(String aarFile1, String aarFile2) throws IOException {
Preconditions.checkArgument(aarFile1.endsWith(".aar"), "invalid aar file: " + aarFile1);
Preconditions.checkArgument(aarFile2.endsWith(".aar"), "invalid aar file: " + aarFile2);
ZipFile zip1 = new ZipFile(aarFile1);
ZipFile zip2 = new ZipFile(aarFile2);
Set<String> zip1Entries =
zip1.stream().map(ZipEntry::getName).collect(ImmutableSet.toImmutableSet());
Set<String> zip2Entries =
zip2.stream().map(ZipEntry::getName).collect(ImmutableSet.toImmutableSet());
if (!zip1Entries.equals(zip2Entries)) {
return false;
}
// Check if all the entries in "classes.jar" in both aar files are the same.
// We expect to find a classes.jar entry in the aar files.
ZipEntry zip1Jar = zip1.getEntry(classesJarInAar);
ZipEntry zip2Jar = zip2.getEntry(classesJarInAar);
if (zip1Jar == null || zip2Jar == null) {
return false;
}
JarInputStream jarIS1 = new JarInputStream(zip1.getInputStream(zip1Jar));
JarInputStream jarIS2 = new JarInputStream(zip2.getInputStream(zip2Jar));
Set<String> jar1Entries = new HashSet<>();
JarEntry jar1Entry = jarIS1.getNextJarEntry();
while (jar1Entry != null) {
jar1Entries.add(jar1Entry.getName());
jar1Entry = jarIS1.getNextJarEntry();
}
Set<String> jar2Entries = new HashSet<>();
JarEntry jar2Entry = jarIS2.getNextJarEntry();
while (jar2Entry != null) {
jar2Entries.add(jar2Entry.getName());
jar2Entry = jarIS2.getNextJarEntry();
}
return jar1Entries.equals(jar2Entries);
}
private void verifyWholeJar(JarInputStream jis, Certificate[] certs) throws IOException, VerificationException
{
for (JarEntry je; (je = jis.getNextJarEntry()) != null; )
{
jis.skip(Long.MAX_VALUE);
verifyJarEntry(je, certs);
}
}
protected void verifyAssembly( File warFile ) throws Exception {
PlutoWebXmlRewriter webXmlRewriter = null;
PortletAppDescriptorService portletSvc = new PortletAppDescriptorServiceImpl();
int entryCount = 0;
ByteArrayOutputStream portletXmlBytes = new ByteArrayOutputStream();
ByteArrayOutputStream webXmlBytes = new ByteArrayOutputStream();
PortletApplicationDefinition portletApp = null;
JarInputStream assembledWarIn = new JarInputStream( new FileInputStream( warFile ) );
JarEntry tempEntry;
while ( ( tempEntry = assembledWarIn.getNextJarEntry() ) != null ) {
entryCount++;
if ( Assembler.PORTLET_XML.equals( tempEntry.getName() ) ) {
IOUtils.copy( assembledWarIn, portletXmlBytes );
portletApp = portletSvc.read( "test", "/test", new ByteArrayInputStream( portletXmlBytes.toByteArray() ) );
}
if ( Assembler.SERVLET_XML.equals( tempEntry.getName() ) ) {
IOUtils.copy( assembledWarIn, webXmlBytes );
webXmlRewriter = new PlutoWebXmlRewriter( new ByteArrayInputStream( webXmlBytes.toByteArray() ) );
}
}
assertTrue( "Assembled WAR file was empty.", entryCount > 0 );
assertNotNull( "Web Application Descripter was null.", webXmlRewriter );
assertNotNull( "Portlet Application Descriptor was null.", portletApp );
assertTrue( "Portlet Application Descriptor doesn't define any portlets.", portletApp.getPortlets().size() > 0 );
assertTrue( "Web Application Descriptor doesn't define any servlets.", webXmlRewriter.hasServlets() );
assertTrue( "Web Application Descriptor doesn't define any servlet mappings.", webXmlRewriter.hasServletMappings() );
PortletDefinition portlet = (PortletDefinition) portletApp.getPortlets().iterator().next();
assertTrue( "Unable to retrieve test portlet named [" + testPortletName + "]", portlet.getPortletName().equals( testPortletName ) );
String servletClassName = webXmlRewriter.getServletClass( testPortletName );
assertNotNull( "Unable to retrieve portlet dispatch for portlet named [" + testPortletName + "]", servletClassName );
assertEquals( "Dispatcher servlet incorrect for test portlet [" + testPortletName + "]", Assembler.DISPATCH_SERVLET_CLASS, servletClassName );
}
private static void findFileInJarWithinJar(String filePath, String packagePath, Set<String> classes) throws IOException {
URL url = new URL("jar", null, 0, filePath);
URLConnection con = url.openConnection();
if (con instanceof JarURLConnection) {
JarURLConnection jarURLConnection = (JarURLConnection) con;
JarInputStream jarInputStream = new JarInputStream(jarURLConnection.getInputStream());
JarEntry entry;
while ((entry = jarInputStream.getNextJarEntry()) != null) {
filterClass(entry.getName(), packagePath, classes);
}
IOUtils.closeQuietly(jarInputStream);
}
}
private static byte[] getEntry(JarInputStream jar, Path entry) throws IOException {
JarEntry je;
while ((je = jar.getNextJarEntry()) != null) {
if (je.getName().equals(entry.toString())) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copy(jar, baos);
baos.close();
return baos.toByteArray();
}
}
return null;
}
void run(JarInputStream in, OutputStream out) throws IOException {
// First thing we do is get the manifest, as JIS does
// not provide the Manifest as an entry.
if (in.getManifest() != null) {
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
in.getManifest().write(tmp);
InputStream tmpIn = new ByteArrayInputStream(tmp.toByteArray());
pkg.addFile(readFile(JarFile.MANIFEST_NAME, tmpIn));
}
for (JarEntry je; (je = in.getNextJarEntry()) != null; ) {
InFile inFile = new InFile(je);
String name = inFile.name;
Package.File bits = readFile(name, in);
Package.File file = null;
// (5078608) : discount the resource files in META-INF
// from segment computation.
long inflen = (isMetaInfFile(name))
? 0L
: inFile.getInputLength();
if ((segmentSize += inflen) > segmentLimit) {
segmentSize -= inflen;
int nextCount = -1; // don't know; it's a stream
flushPartial(out, nextCount);
}
if (verbose > 1) {
Utils.log.fine("Reading " + name);
}
assert(je.isDirectory() == name.endsWith("/"));
if (isClassFile(name)) {
file = readClass(name, bits.getInputStream());
}
if (file == null) {
file = bits;
pkg.addFile(file);
}
inFile.copyTo(file);
noteRead(inFile);
}
flushAll(out);
}
void run(JarInputStream in, OutputStream out) throws IOException {
// First thing we do is get the manifest, as JIS does
// not provide the Manifest as an entry.
if (in.getManifest() != null) {
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
in.getManifest().write(tmp);
InputStream tmpIn = new ByteArrayInputStream(tmp.toByteArray());
pkg.addFile(readFile(JarFile.MANIFEST_NAME, tmpIn));
}
for (JarEntry je; (je = in.getNextJarEntry()) != null; ) {
InFile inFile = new InFile(je);
String name = inFile.name;
Package.File bits = readFile(name, in);
Package.File file = null;
// (5078608) : discount the resource files in META-INF
// from segment computation.
long inflen = (isMetaInfFile(name))
? 0L
: inFile.getInputLength();
if ((segmentSize += inflen) > segmentLimit) {
segmentSize -= inflen;
int nextCount = -1; // don't know; it's a stream
flushPartial(out, nextCount);
}
if (verbose > 1) {
Utils.log.fine("Reading " + name);
}
assert(je.isDirectory() == name.endsWith("/"));
if (isClassFile(name)) {
file = readClass(name, bits.getInputStream());
}
if (file == null) {
file = bits;
pkg.addFile(file);
}
inFile.copyTo(file);
noteRead(inFile);
}
flushAll(out);
}
void run(JarInputStream in, OutputStream out) throws IOException {
// First thing we do is get the manifest, as JIS does
// not provide the Manifest as an entry.
if (in.getManifest() != null) {
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
in.getManifest().write(tmp);
InputStream tmpIn = new ByteArrayInputStream(tmp.toByteArray());
pkg.addFile(readFile(JarFile.MANIFEST_NAME, tmpIn));
}
for (JarEntry je; (je = in.getNextJarEntry()) != null; ) {
InFile inFile = new InFile(je);
String name = inFile.name;
Package.File bits = readFile(name, in);
Package.File file = null;
// (5078608) : discount the resource files in META-INF
// from segment computation.
long inflen = (isMetaInfFile(name))
? 0L
: inFile.getInputLength();
if ((segmentSize += inflen) > segmentLimit) {
segmentSize -= inflen;
int nextCount = -1; // don't know; it's a stream
flushPartial(out, nextCount);
}
if (verbose > 1) {
Utils.log.fine("Reading " + name);
}
assert(je.isDirectory() == name.endsWith("/"));
if (isClassFile(name)) {
file = readClass(name, bits.getInputStream());
}
if (file == null) {
file = bits;
pkg.addFile(file);
}
inFile.copyTo(file);
noteRead(inFile);
}
flushAll(out);
}
void run(JarInputStream in, OutputStream out) throws IOException {
// First thing we do is get the manifest, as JIS does
// not provide the Manifest as an entry.
if (in.getManifest() != null) {
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
in.getManifest().write(tmp);
InputStream tmpIn = new ByteArrayInputStream(tmp.toByteArray());
pkg.addFile(readFile(JarFile.MANIFEST_NAME, tmpIn));
}
for (JarEntry je; (je = in.getNextJarEntry()) != null; ) {
InFile inFile = new InFile(je);
String name = inFile.name;
Package.File bits = readFile(name, in);
Package.File file = null;
// (5078608) : discount the resource files in META-INF
// from segment computation.
long inflen = (isMetaInfFile(name))
? 0L
: inFile.getInputLength();
if ((segmentSize += inflen) > segmentLimit) {
segmentSize -= inflen;
int nextCount = -1; // don't know; it's a stream
flushPartial(out, nextCount);
}
if (verbose > 1) {
Utils.log.fine("Reading " + name);
}
assert(je.isDirectory() == name.endsWith("/"));
if (isClassFile(name)) {
file = readClass(name, bits.getInputStream());
}
if (file == null) {
file = bits;
pkg.addFile(file);
}
inFile.copyTo(file);
noteRead(inFile);
}
flushAll(out);
}
@Test
public void testGUVNOR578_2() throws Exception {
final MapBackedClassLoader loader = new MapBackedClassLoader( this.getClass().getClassLoader() );
final JarInputStream jis = new JarInputStream( this.getClass().getResourceAsStream( "/primespoc.jar" ) );
JarEntry entry = null;
final byte[] buf = new byte[1024];
int len = 0;
while ( (entry = jis.getNextJarEntry()) != null ) {
if ( !entry.isDirectory() ) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
while ( (len = jis.read( buf )) >= 0 ) {
out.write( buf,
0,
len );
}
loader.addResource( entry.getName(),
out.toByteArray() );
}
}
final List<JarInputStream> jarInputStreams = new ArrayList<JarInputStream>();
jarInputStreams.add(jis);
final KnowledgeBuilderConfiguration conf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(null, loader);
final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(conf);
final String header = "import fr.gouv.agriculture.dag.agorha.business.primes.SousPeriodePrimeAgent\n";
kbuilder.add(ResourceFactory.newByteArrayResource(header.getBytes()), ResourceType.DRL);
assertFalse(kbuilder.hasErrors());
final String passingRule = "rule \"rule1\"\n"
+ "dialect \"mvel\"\n"
+ "when\n"
+ "SousPeriodePrimeAgent( echelle == \"abc\" )"
+ "then\n"
+ "end\n";
final String failingRule = "rule \"rule2\"\n"
+ "dialect \"mvel\"\n"
+ "when\n"
+ "SousPeriodePrimeAgent( quotiteRemuneration == 123 , echelle == \"abc\" )"
+ "then\n"
+ "end\n";
kbuilder.add(ResourceFactory.newByteArrayResource(passingRule.getBytes()), ResourceType.DRL);
assertFalse(kbuilder.hasErrors());
kbuilder.add(ResourceFactory.newByteArrayResource(failingRule.getBytes()), ResourceType.DRL);
assertFalse(kbuilder.hasErrors());
}
void run(JarInputStream in, OutputStream out) throws IOException {
// First thing we do is get the manifest, as JIS does
// not provide the Manifest as an entry.
if (in.getManifest() != null) {
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
in.getManifest().write(tmp);
InputStream tmpIn = new ByteArrayInputStream(tmp.toByteArray());
pkg.addFile(readFile(JarFile.MANIFEST_NAME, tmpIn));
}
for (JarEntry je; (je = in.getNextJarEntry()) != null; ) {
InFile inFile = new InFile(je);
String name = inFile.name;
Package.File bits = readFile(name, in);
Package.File file = null;
// (5078608) : discount the resource files in META-INF
// from segment computation.
long inflen = (inFile.isMetaInfFile())
? 0L
: inFile.getInputLength();
if ((segmentSize += inflen) > segmentLimit) {
segmentSize -= inflen;
int nextCount = -1; // don't know; it's a stream
flushPartial(out, nextCount);
}
if (verbose > 1) {
Utils.log.fine("Reading " + name);
}
assert(je.isDirectory() == name.endsWith("/"));
if (inFile.mustProcess()) {
file = readClass(name, bits.getInputStream());
}
if (file == null) {
file = bits;
pkg.addFile(file);
}
inFile.copyTo(file);
noteRead(inFile);
}
flushAll(out);
}
protected void
readPatchEntries(
InputStream is )
throws IOException
{
JarInputStream jis = new JarInputStream(is );
while( true ){
JarEntry ent = jis.getNextJarEntry();
if ( ent == null ){
break;
}
if ( ent.isDirectory()){
continue;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
while( true ){
int l = jis.read( buffer );
if ( l <= 0 ){
break;
}
baos.write( buffer, 0, l );
}
patch_entries.put( ent.getName(), new ByteArrayInputStream( baos.toByteArray()));
}
}