1 /* 2 * Copyright (C) 2021 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.annotationvisitor; 18 19 import org.apache.bcel.classfile.ClassParser; 20 import org.apache.bcel.classfile.JavaClass; 21 22 import java.io.IOException; 23 import java.util.Objects; 24 import java.util.stream.Stream; 25 import java.util.zip.ZipEntry; 26 import java.util.zip.ZipFile; 27 28 /** 29 * Reads {@link JavaClass} members from a zip/jar file, providing a stream of them for processing. 30 * Any errors are reported via {@link Status#error(Throwable)}. 31 */ 32 public class JarReader { 33 34 private final Status mStatus; 35 private final String mFileName; 36 private final ZipFile mZipFile; 37 JarReader(Status s, String filename)38 public JarReader(Status s, String filename) throws IOException { 39 mStatus = s; 40 mFileName = filename; 41 mZipFile = new ZipFile(mFileName); 42 } 43 openZipEntry(ZipEntry e)44 private JavaClass openZipEntry(ZipEntry e) { 45 try { 46 mStatus.debug("Reading %s from %s", e.getName(), mFileName); 47 return new ClassParser(mZipFile.getInputStream(e), e.getName()).parse(); 48 } catch (IOException ioe) { 49 mStatus.error(ioe); 50 return null; 51 } 52 } 53 54 stream()55 public Stream<JavaClass> stream() { 56 return mZipFile.stream() 57 .filter(zipEntry -> zipEntry.getName().endsWith(".class")) 58 .map(zipEntry -> openZipEntry(zipEntry)) 59 .filter(Objects::nonNull); 60 } 61 close()62 public void close() throws IOException { 63 mZipFile.close(); 64 } 65 } 66