001/* 002 * Copyright 2010-2017 The jdependency developers. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.vafer.jdependency.utils; 017 018import java.io.IOException; 019import java.io.InputStream; 020import java.util.HashSet; 021import java.util.Set; 022import java.util.jar.JarEntry; 023import java.util.jar.JarInputStream; 024 025import org.apache.commons.io.IOUtils; 026import org.apache.commons.io.output.NullOutputStream; 027import org.objectweb.asm.ClassReader; 028import org.vafer.jdependency.asm.DependenciesClassAdapter; 029 030public final class DependencyUtils { 031 032 public static Set<String> getDependenciesOfJar( final InputStream pInputStream ) throws IOException { 033 final JarInputStream inputStream = new JarInputStream(pInputStream); 034 final NullOutputStream nullStream = new NullOutputStream(); 035 final Set<String> dependencies = new HashSet<String>(); 036 try { 037 while (true) { 038 final JarEntry entry = inputStream.getNextJarEntry(); 039 040 if (entry == null) { 041 break; 042 } 043 044 if (entry.isDirectory()) { 045 // ignore directory entries 046 IOUtils.copy(inputStream, nullStream); 047 continue; 048 } 049 050 final String name = entry.getName(); 051 052 if (name.endsWith(".class")) { 053 final DependenciesClassAdapter v = new DependenciesClassAdapter(); 054 new ClassReader( inputStream ).accept( v, 0 ); 055 dependencies.addAll(v.getDependencies()); 056 } else { 057 IOUtils.copy(inputStream, nullStream); 058 } 059 } 060 } finally { 061 inputStream.close(); 062 } 063 064 return dependencies; 065 } 066 067 public static Set<String> getDependenciesOfClass( final InputStream pInputStream ) throws IOException { 068 final DependenciesClassAdapter v = new DependenciesClassAdapter(); 069 new ClassReader( pInputStream ).accept( v, ClassReader.EXPAND_FRAMES ); 070 final Set<String> depNames = v.getDependencies(); 071 return depNames; 072 } 073 074 public static Set<String> getDependenciesOfClass( final Class<?> pClass ) throws IOException { 075 final String resource = "/" + pClass.getName().replace('.', '/') + ".class"; 076 return getDependenciesOfClass(pClass.getResourceAsStream(resource)); 077 } 078 079}