下面列出了java.util.jar.JarEntry#getName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void doJar(String a, File source, File dest,
ClassReader options, String encoding,
Boolean contError) throws IOException {
try {
JarFile jf = new JarFile(source);
for (JarEntry je : Collections.list(jf.entries())) {
String name = je.getName();
if (!name.endsWith(".class")) {
continue;
}
try {
doStream(name, jf.getInputStream(je), dest, options, encoding);
} catch (Exception e) {
if (contError) {
System.out.println("Error processing " + source + ": " + e);
e.printStackTrace();
continue;
}
}
}
} catch (IOException ioe) {
throw ioe;
}
}
@Test
public void createJarFileTest() {
try {
final File[] files = this.folder.listFiles();
for (final File file : files) {
this.providerFile.zipProject(file.getAbsolutePath(), this.jarFile, true);
}
final JarFile jar = new JarFile(this.jarFile);
final Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
final String entryName = entry.getName();
this.elementExists = fileExists(files, entryName);
}
assertEquals(this.elementExists, true);
jar.close();
}
catch (final IOException e) {
e.printStackTrace();
}
}
/**
* Unpacks the NAR to the specified directory. Creates a checksum file that used to determine if future expansion is
* necessary.
*
* @param workingDirectory
* the root directory to which the NAR should be unpacked.
* @throws IOException
* if the NAR could not be unpacked.
*/
private static void unpack(final File nar, final File workingDirectory, final byte[] hash) throws IOException {
try (JarFile jarFile = new JarFile(nar)) {
Enumeration<JarEntry> jarEntries = jarFile.entries();
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
String name = jarEntry.getName();
File f = new File(workingDirectory, name);
if (jarEntry.isDirectory()) {
FileUtils.ensureDirectoryExistAndCanReadAndWrite(f);
} else {
makeFile(jarFile.getInputStream(jarEntry), f);
}
}
}
final File hashFile = new File(workingDirectory, HASH_FILENAME);
try (final FileOutputStream fos = new FileOutputStream(hashFile)) {
fos.write(hash);
}
}
private void testJar(final File file) throws Exception {
System.out.println("parsing " + file);
try (JarFile jar = new JarFile(file)) {
final Enumeration<JarEntry> en = jar.entries();
while (en.hasMoreElements()) {
final JarEntry e = en.nextElement();
final String name = e.getName();
if (name.endsWith(".class")) {
// System.out.println("parsing " + name);
try (InputStream in = jar.getInputStream(e)) {
final ClassParser parser = new ClassParser(in, name);
final JavaClass jc = parser.parse();
compare(jc, jar.getInputStream(e), name);
}
}
}
}
}
@Override
public Providers filter(JarEntry jarEntry) {
final String jarEntryName = jarEntry.getName();
if (!jarEntryName.startsWith(SERVICE_LOADER)) {
return null;
}
if (jarEntry.isDirectory()) {
return null;
}
if (jarEntryName.indexOf('/', SERVICE_LOADER.length()) != -1) {
return null;
}
try {
InputStream inputStream = jarFile.getInputStream(jarEntry);
ServiceDescriptorParser parser = new ServiceDescriptorParser();
List<String> serviceImplClassName = parser.parse(inputStream);
String serviceClassName = jarEntryName.substring(SERVICE_LOADER.length());
return new Providers(serviceClassName, serviceImplClassName);
} catch (IOException e) {
throw new IllegalStateException(jarFile.getName() + " File read fail ", e);
}
}
public static byte[] readFileFromJar(File file, String path) throws IOException {
JarFile jarFile = new JarFile(file.getAbsolutePath());
Enumeration<JarEntry> entries = jarFile.entries();
JarEntry configEntry = null;
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
String name = jarEntry.getName();
if (path.equals(name)) {
configEntry = jarEntry;
break;
}
}
if (configEntry == null) return null;
InputStream input = jarFile.getInputStream(configEntry);
byte[] buffer = new byte[4096];
int n;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
private static void doJar(String a, File source, File dest,
ClassReader options, String encoding,
Boolean contError) throws IOException {
try {
JarFile jf = new JarFile(source);
for (JarEntry je : Collections.list(jf.entries())) {
String name = je.getName();
if (!name.endsWith(".class")) {
continue;
}
try {
doStream(name, jf.getInputStream(je), dest, options, encoding);
} catch (Exception e) {
if (contError) {
System.out.println("Error processing " + source + ": " + e);
e.printStackTrace();
continue;
}
}
}
} catch (IOException ioe) {
throw ioe;
}
}
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
try {
if (jf1.size() != jf2.size()) {
throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
+ " have different number of entries");
}
for (JarEntry elem1 : Collections.list(jf1.entries())) {
JarEntry elem2 = jf2.getJarEntry(elem1.getName());
if (elem2 == null) {
throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
}
if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
throw new Exception("The crc of " + elem1.getName() + " is different.");
}
}
} finally {
jf1.close();
jf2.close();
}
}
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 static Map<String, byte[]> readJarEntries(Path jarPath) throws IOException {
Map<String, byte[]> allJarEntries = new TreeMap<>();
try (JarInputStream in = new JarInputStream(new FileInputStream(jarPath.toFile()))) {
// Add manifest
byte[] manifest = manifestAsBytes(in);
allJarEntries.put(JarFile.MANIFEST_NAME, manifest);
// Add other entries
JarEntry nextEntry;
while ((nextEntry = in.getNextJarEntry()) != null) {
String name = nextEntry.getName();
byte[] bytes = ByteStreams.toByteArray(in);
allJarEntries.put(name, bytes);
in.closeEntry();
}
}
return allJarEntries;
}
public static ArrayList<String> getEntryNameListing(final JarFile jar, final JarFilter filter) {
final ArrayList<String> result = new ArrayList<>();
final Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
final String path = entry.getName();
final int pos = path.lastIndexOf('/');
final String dirName = (pos >= 0) ? path.substring(0, pos) : "";
final String name = (pos >= 0) ? path.substring(pos + 1) : path;
if (filter.accept(dirName, name)) {
result.add(path);
}
}
return result;
}
private void parseExtensionDocs(final JarInputStream jarInputStream, final BundleDetails.Builder builder) throws IOException {
JarEntry jarEntry;
boolean foundExtensionDocs = false;
while((jarEntry = jarInputStream.getNextJarEntry()) != null) {
final String jarEntryName = jarEntry.getName();
if (EXTENSION_DESCRIPTOR_ENTRY.equals(jarEntryName)) {
try {
final byte[] rawDocsContent = toByteArray(jarInputStream);
final ExtensionManifestParser docsParser = new JacksonExtensionManifestParser();
final InputStream inputStream = new NonCloseableInputStream(new ByteArrayInputStream(rawDocsContent));
final ExtensionManifest extensionManifest = docsParser.parse(inputStream);
builder.addExtensions(extensionManifest.getExtensions());
builder.systemApiVersion(extensionManifest.getSystemApiVersion());
foundExtensionDocs = true;
} catch (Exception e) {
throw new BundleException("Unable to obtain extension info for bundle due to: " + e.getMessage(), e);
}
} else {
final Matcher matcher = ADDITIONAL_DETAILS_ENTRY_PATTERN.matcher(jarEntryName);
if (matcher.matches()) {
final String extensionName = matcher.group(1);
final String additionalDetailsContent = new String(toByteArray(jarInputStream), StandardCharsets.UTF_8);
builder.addAdditionalDetails(extensionName, additionalDetailsContent);
}
}
}
if (!foundExtensionDocs) {
throw new BundleException("Unable to find descriptor at '" + EXTENSION_DESCRIPTOR_ENTRY + "'. " +
"This NAR may need to be rebuilt with the latest version of the NiFi NAR Maven Plugin.");
}
}
public static void extractJar(JarFile jf, File where) throws Exception {
for (JarEntry file : Collections.list(jf.entries())) {
File out = new File(where, file.getName());
if (file.isDirectory()) {
out.mkdirs();
continue;
}
File parent = out.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
InputStream is = null;
OutputStream os = null;
try {
is = jf.getInputStream(file);
os = new FileOutputStream(out);
while (is.available() > 0) {
os.write(is.read());
}
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
}
}
public static Set<String> readStrings(@Nonnull File in) throws IOException {
Set<String> strings = new HashSet<String>();
JarFile file = new JarFile(in);
for (JarEntry entry : Collections.list(file.entries())) {
String name = entry.getName();
if (!name.endsWith(".class")) {
continue;
}
name = name.substring(0, name.length() - 6);
strings.add(name.replace(File.pathSeparator, "."));
}
return strings;
}
private void preloadJarEntry(Object obj) {
long start, elapsed;
JarEntry entry = (JarEntry)obj;
String name = entry.getName();
int classIndex = name.indexOf(".class");
if (classIndex != -1) {
long size = entry.getSize();
//long compressedSize = entry.getCompressedSize();
String classFileName = name.replace('/', '.');
String className = classFileName.substring(0, classIndex);
preloadClass(className, size);
}
}
protected JarEntry nextEntry() {
while (entries.hasMoreElements()) {
JarEntry e = entries.nextElement();
String name = e.getName();
if (name.endsWith(".class")) {
return e;
}
}
return null;
}
public void run(String[] args) throws IOException, ConstantPoolException {
JarFile jar = new JarFile(args[0]);
Set<JarEntry> entries = getNativeClasses(jar);
for (JarEntry e: entries) {
String name = e.getName();
String className = name.substring(0, name.length() - 6).replace("/", ".");
System.out.println(className);
}
}
/**
*
* @param jarFileURL
* @param sourcePath
* @param destination
* @param overwrite
* @throws Exception
*/
protected static void copyJarPath(URL jarFileURL, String sourcePath, File destination, boolean overwrite)throws Exception{
//URL jarFileURL = ResourceUtils.extractJarFileURL(url);
if(!sourcePath.endsWith("/")){
sourcePath += "/";
}
String root = jarFileURL.toString() + "!/";
if(!root.startsWith("jar:")){
root = "jar:" + root;
}
JarFile jarFile = new JarFile(new File(jarFileURL.toURI()));
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
String name = jarEntry.getName();
//log.debug(name + "." + sourcePath + "." + name.startsWith(sourcePath));
if(name.startsWith(sourcePath)){
String relativePath = name.substring(sourcePath.length());
//log.debug("relativePath: " + relativePath);
if(relativePath != null && relativePath.length() > 0){
File tmp = new File(destination, relativePath);
//not exists or overwrite permitted
if(overwrite || !tmp.exists()){
if(jarEntry.isDirectory()){
tmp.mkdirs();
if(IS_DEBUG_ENABLED){
log.debug("Create directory: " + tmp);
}
}else{
File parent = tmp.getParentFile();
if(!parent.exists()){
parent.mkdirs();
}
//1.FileCopyUtils.copy
//InputStream is = jarFile.getInputStream(jarEntry);
//FileCopyUtils.copy(is, new FileOutputStream(tmp));
//2. url copy
URL u = new URL(root + name);
//log.debug(u.toString());
FileUtils.copyURLToFile(u, tmp);
if(IS_DEBUG_ENABLED){
log.debug("Copyed file '" + u + "' to '" + tmp + "'.");
}
}
}
}
}
}
try{
jarFile.close();
}catch(Exception ie){
}
}
public ValidationResult afterSelectClass() {
List<String> driverClasses = new ArrayList<>();
AllSetting setting = new AllSetting();
setting.setDriverPaths(driverTable.drivers.getValue());
List<String> jar_maven_paths = setting.getDriverPaths();
try {
List<URL> urls = new ArrayList<>();
for (String maven_path : jar_maven_paths) {
URL url = new URL(removeQuote(maven_path));
urls.add(url);
}
URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[0]), this.getClass().getClassLoader());
for (URL jarUrl : urls) {
try (JarInputStream jarInputStream = new JarInputStream(jarUrl.openStream())) {
JarEntry nextJarEntry = jarInputStream.getNextJarEntry();
while (nextJarEntry != null) {
boolean isFile = !nextJarEntry.isDirectory();
if (isFile) {
String name = nextJarEntry.getName();
if (name != null && name.toLowerCase().endsWith(".class")) {
String className = changeFileNameToClassName(name);
try {
Class clazz = classLoader.loadClass(className);
if (Driver.class.isAssignableFrom(clazz)) {
driverClasses.add(clazz.getName());
}
} catch (Throwable th) {
// ignore all the exceptions, especially the class not found exception when look up a class
// outside the jar
}
}
}
nextJarEntry = jarInputStream.getNextJarEntry();
}
}
}
} catch (Exception ex) {
return new ValidationResult(ValidationResult.Result.ERROR, ex.getMessage());
}
if (driverClasses.isEmpty()) {
return new ValidationResult(ValidationResult.Result.ERROR,
"not found any Driver class, please make sure the jar is right");
}
driverClass.setPossibleValues(driverClasses);
driverClass.setValue(driverClasses.get(0));
return ValidationResult.OK;
}
/**
* As of TDCH 1.4.1, integration with Teradata wallet only works with hadoop jar command line command.
* This is mainly because TDCH depends on the behavior of hadoop jar command line which extracts jar file
* into hadoop tmp folder.
*
* This method will extract tdchJarfile and place it into temporary folder, and also add jvm shutdown hook
* to delete the directory when JVM shuts down.
* @param tdchJarFile TDCH jar file.
*/
public static void initialize(File tmpDir, File tdchJarFile) {
synchronized (TeraDataWalletInitializer.class) {
if (tdchJarExtractedDir != null) {
return;
}
if (tdchJarFile == null) {
throw new IllegalArgumentException("TDCH jar file cannot be null.");
}
if (!tdchJarFile.exists()) {
throw new IllegalArgumentException("TDCH jar file does not exist. " + tdchJarFile.getAbsolutePath());
}
try {
//Extract TDCH jar.
File unJarDir = createUnjarDir(new File(tmpDir.getAbsolutePath() + File.separator + UNJAR_DIR_NAME));
JarFile jar = new JarFile(tdchJarFile);
Enumeration<JarEntry> enumEntries = jar.entries();
while (enumEntries.hasMoreElements()) {
JarEntry srcFile = enumEntries.nextElement();
File destFile = new File(unJarDir + File.separator + srcFile.getName());
if (srcFile.isDirectory()) { // if its a directory, create it
destFile.mkdir();
continue;
}
InputStream is = jar.getInputStream(srcFile);
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(destFile));
IOUtils.copy(is, os);
close(os);
close(is);
}
jar.close();
tdchJarExtractedDir = unJarDir;
} catch (IOException e) {
throw new RuntimeException("Failed while extracting TDCH jar file.", e);
}
}
logger.info("TDCH jar has been extracted into directory: " + tdchJarExtractedDir.getAbsolutePath());
}