Java Code Examples for org.apache.bcel.classfile.ClassParser#parse()

The following examples show how to use org.apache.bcel.classfile.ClassParser#parse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClassDumperTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testListInnerClasses() throws IOException {
  InputStream classFileInputStream = URLClassLoader.getSystemResourceAsStream(
      EXAMPLE_CLASS_FILE);
  ClassParser parser = new ClassParser(classFileInputStream, EXAMPLE_CLASS_FILE);
  JavaClass javaClass = parser.parse();

  Set<String> innerClassNames = ClassDumper.listInnerClassNames(javaClass);
  Truth.assertThat(innerClassNames).containsExactly(
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreFutureStub",
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreMethodDescriptorSupplier",
      "com.google.firestore.v1beta1.FirestoreGrpc$1",
      "com.google.firestore.v1beta1.FirestoreGrpc$MethodHandlers",
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreStub",
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreBaseDescriptorSupplier",
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreBlockingStub",
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreImplBase",
      "com.google.firestore.v1beta1.FirestoreGrpc$FirestoreFileDescriptorSupplier"
  );
}
 
Example 2
Source File: RootBuilder.java    From android-classyshark with Apache License 2.0 6 votes vote down vote up
private ClassNode fillFromJar(File file) {

        ClassNode rootNode = new ClassNode(file.getName());
        try {
            JarFile theJar = new JarFile(file);
            Enumeration<? extends JarEntry> en = theJar.entries();

            while (en.hasMoreElements()) {
                JarEntry entry = en.nextElement();
                if (entry.getName().endsWith(".class")) {
                    ClassParser cp = new ClassParser(
                            theJar.getInputStream(entry), entry.getName());
                    JavaClass jc = cp.parse();
                    ClassInfo classInfo = new ClassInfo(jc.getClassName(),
                            jc.getMethods().length);
                    rootNode.add(classInfo);
                }
            }
        } catch (IOException e) {
            System.err.println("Error reading file: " + file + ". " + e.getMessage());
            e.printStackTrace(System.err);
        }

        return rootNode;
    }
 
Example 3
Source File: patchclass.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    final String[] file_name = new String[argv.length];
    int files = 0;

    if (argv.length < 3) {
        System.err.println("Usage: patch <oldstring> <newstring> file1.class ...");
        System.exit(-1);
    }

    for (int i = 2; i < argv.length; i++) {
        file_name[files++] = argv[i];
    }

    for (int i = 0; i < files; i++) {
        final ClassParser parser = new ClassParser(file_name[i]);
        final JavaClass java_class = parser.parse();

        patchIt(argv[0], argv[1], java_class.getConstantPool().getConstantPool());

        // Dump the changed class to a new file
        java_class.dump("_" + file_name[i]);
        System.out.println("Results saved in: _" + file_name[i]);
    }
}
 
Example 4
Source File: ClassLoaderRepository.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * Lookup a JavaClass object from the Class Name provided.
 */
@Override
public JavaClass loadClass(final String className) throws ClassNotFoundException {
    final String classFile = className.replace('.', '/');
    JavaClass RC = findClass(className);
    if (RC != null) {
        return RC;
    }
    try (InputStream is = loader.getResourceAsStream(classFile + ".class")) {
        if (is == null) {
            throw new ClassNotFoundException(className + " not found.");
        }
        final ClassParser parser = new ClassParser(is, className);
        RC = parser.parse();
        storeClass(RC);
        return RC;
    } catch (final IOException e) {
        throw new ClassNotFoundException(className + " not found: " + e, e);
    }
}
 
Example 5
Source File: ClassLoader.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * Override this method to create you own classes on the fly. The
 * name contains the special token $$BCEL$$. Everything before that
 * token is considered to be a package name. You can encode your own
 * arguments into the subsequent string. You must ensure however not
 * to use any "illegal" characters, i.e., characters that may not
 * appear in a Java class name too
 * <p>
 * The default implementation interprets the string as a encoded compressed
 * Java class, unpacks and decodes it with the Utility.decode() method, and
 * parses the resulting byte array and returns the resulting JavaClass object.
 * </p>
 *
 * @param class_name compressed byte code with "$$BCEL$$" in it
 */
protected JavaClass createClass( final String class_name ) {
    final int index = class_name.indexOf(BCEL_TOKEN);
    final String real_name = class_name.substring(index + BCEL_TOKEN.length());
    JavaClass clazz = null;
    try {
        final byte[] bytes = Utility.decode(real_name, true);
        final ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), "foo");
        clazz = parser.parse();
    } catch (final IOException e) {
        e.printStackTrace();
        return null;
    }
    // Adapt the class name to the passed value
    final ConstantPool cp = clazz.getConstantPool();
    final ConstantClass cl = (ConstantClass) cp.getConstant(clazz.getClassNameIndex(),
            Const.CONSTANT_Class);
    final ConstantUtf8 name = (ConstantUtf8) cp.getConstant(cl.getNameIndex(),
            Const.CONSTANT_Utf8);
    name.setBytes(class_name.replace('.', '/'));
    return clazz;
}
 
Example 6
Source File: JdkGenericDumpTestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
private void testJar(final File file) throws Exception {
    System.out.println(file);
    try (JarFile jar = new JarFile(file)) {
        final Enumeration<JarEntry> en = jar.entries();
        while (en.hasMoreElements()) {
            final JarEntry jarEntry = en.nextElement();
            final String name = jarEntry.getName();
            if (name.endsWith(".class")) {
                // System.out.println("- " + name);
                try (InputStream inputStream = jar.getInputStream(jarEntry)) {
                    final ClassParser classParser = new ClassParser(inputStream, name);
                    final JavaClass javaClass = classParser.parse();
                    for (final Method method : javaClass.getMethods()) {
                        compare(name, method);
                    }
                }
            }
        }
    }
}
 
Example 7
Source File: PrintClass.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void printClass(ClassParser parser) throws IOException {
    JavaClass java_class;
    java_class = parser.parse();

    if (superClasses) {
        try {
            while (java_class != null) {
                System.out.print(java_class.getClassName() + "  ");
                java_class = java_class.getSuperClass();
            }
        } catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());

        }
        System.out.println();
        return;
    }
    if (constants || code) {
        System.out.println(java_class); // Dump the contents
    }
    if (constants) {
        System.out.println(java_class.getConstantPool());
    }

    if (code) {
        printCode(java_class.getMethods());
    }
}
 
Example 8
Source File: URLClassPath.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Look up a class from the classpath.
 *
 * @param className
 *            name of class to look up
 * @return the JavaClass object for the class
 * @throws ClassNotFoundException
 *             if the class couldn't be found
 */
public JavaClass lookupClass(String className) throws ClassNotFoundException {
    if (classesThatCantBeFound.contains(className)) {
        throw new ClassNotFoundException("Error while looking for class " + className + ": class not found");
    }
    String resourceName = className.replace('.', '/') + ".class";
    InputStream in = null;
    boolean parsedClass = false;

    try {

        in = getInputStreamForResource(resourceName);
        if (in == null) {
            classesThatCantBeFound.add(className);
            throw new ClassNotFoundException("Error while looking for class " + className + ": class not found");
        }

        ClassParser classParser = new ClassParser(in, resourceName);
        JavaClass javaClass = classParser.parse();
        parsedClass = true;

        return javaClass;
    } catch (IOException e) {
        classesThatCantBeFound.add(className);
        throw new ClassNotFoundException("IOException while looking for class " + className, e);
    } finally {
        if (in != null && !parsedClass) {
            try {
                in.close();
            } catch (IOException ignore) {
                // Ignore
            }
        }
    }
}
 
Example 9
Source File: JdkGenericDumpTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
private void find(final Path path) throws IOException {
    final Path name = path.getFileName();
    if (name != null && matcher.matches(name)) {
        try (final InputStream inputStream = Files.newInputStream(path)) {
            final ClassParser classParser = new ClassParser(inputStream, name.toAbsolutePath().toString());
            final JavaClass javaClass = classParser.parse();
            Assert.assertNotNull(javaClass);
        }

    }
}
 
Example 10
Source File: Class2HTMLTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public void testConvertJavaUtil() throws Exception {
    final File outputDir = new File("target/test-output/html");
    if (!outputDir.mkdirs()) { // either was not created or already existed
        Assert.assertTrue(outputDir.isDirectory()); // fail if missing
    }

    try (FileInputStream file = new FileInputStream("target/test-classes/Java8Example.class")) {

        final ClassParser parser = new ClassParser(file, "Java8Example.class");

        new Class2HTML(parser.parse(), outputDir.getAbsolutePath() + "/");
    }
}
 
Example 11
Source File: NativeJavahMojo.java    From maven-native with MIT License 4 votes vote down vote up
/**
 * Get applicable class names to be "javahed"
 */

private void discoverAdditionalJNIClassName()
    throws MojoExecutionException
{
    if ( !this.javahSearchJNIFromDependencies )
    {
        return;
    }

    // scan the immediate dependency list for jni classes

    List<Artifact> artifacts = this.getJavahArtifacts();

    for ( Iterator<Artifact> iter = artifacts.iterator(); iter.hasNext(); )
    {
        Artifact artifact = iter.next();

        this.getLog().info( "Parsing " + artifact.getFile() + " for native classes." );

        try
        {
            ZipFile zipFile = new ZipFile( artifact.getFile() );
            Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();

            while ( zipEntries.hasMoreElements() )
            {
                ZipEntry zipEntry = zipEntries.nextElement();

                if ( "class".equals( FileUtils.extension( zipEntry.getName() ) ) )
                {
                    ClassParser parser = new ClassParser( artifact.getFile().getPath(), zipEntry.getName() );

                    JavaClass clazz = parser.parse();

                    Method[] methods = clazz.getMethods();

                    for ( int j = 0; j < methods.length; ++j )
                    {
                        if ( methods[j].isNative() )
                        {
                            javahClassNames.add( clazz.getClassName() );

                            this.getLog().info( "Found native class: " + clazz.getClassName() );

                            break;
                        }
                    }
                }
            } // endwhile

            // not full proof
            zipFile.close();
        }
        catch ( IOException ioe )
        {
            throw new MojoExecutionException( "Error searching for native class in " + artifact.getFile(), ioe );
        }
    }

}
 
Example 12
Source File: ClassFilePreDecompilationScan.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
private void addClassFileMetadata(GraphRewrite event, EvaluationContext context, JavaClassFileModel javaClassFileModel)
{
    try (FileInputStream fis = new FileInputStream(javaClassFileModel.getFilePath()))
    {
        final ClassParser parser = new ClassParser(fis, javaClassFileModel.getFilePath());
        final JavaClass bcelJavaClass = parser.parse();
        final String packageName = bcelJavaClass.getPackageName();

        final String qualifiedName = bcelJavaClass.getClassName();

        final JavaClassService javaClassService = new JavaClassService(event.getGraphContext());
        final JavaClassModel javaClassModel = javaClassService.create(qualifiedName);
        int majorVersion = bcelJavaClass.getMajor();
        int minorVersion = bcelJavaClass.getMinor();

        String simpleName = qualifiedName;
        if (packageName != null && !packageName.isEmpty() && simpleName != null)
        {
            simpleName = StringUtils.substringAfterLast(simpleName, ".");
        }

        javaClassFileModel.setMajorVersion(majorVersion);
        javaClassFileModel.setMinorVersion(minorVersion);
        javaClassFileModel.setPackageName(packageName);

        javaClassModel.setSimpleName(simpleName);
        javaClassModel.setPackageName(packageName);
        javaClassModel.setQualifiedName(qualifiedName);
        javaClassModel.setClassFile(javaClassFileModel);
        javaClassModel.setPublic(bcelJavaClass.isPublic());
        javaClassModel.setInterface(bcelJavaClass.isInterface());

        final String[] interfaceNames = bcelJavaClass.getInterfaceNames();
        if (interfaceNames != null)
        {
            for (final String interfaceName : interfaceNames)
            {
                JavaClassModel interfaceModel = javaClassService.getOrCreatePhantom(interfaceName);
                javaClassService.addInterface(javaClassModel, interfaceModel);
            }
        }

        String superclassName = bcelJavaClass.getSuperclassName();
        if (!bcelJavaClass.isInterface() && !StringUtils.isBlank(superclassName))
            javaClassModel.setExtends(javaClassService.getOrCreatePhantom(superclassName));

        javaClassFileModel.setJavaClass(javaClassModel);
    }
    catch (Exception ex)
    {
        String nl = ex.getMessage() != null ? Util.NL + "\t" : " ";
        final String message = "BCEL was unable to parse class file '" + javaClassFileModel.getFilePath() + "':" + nl + ex.toString();
        LOG.log(Level.WARNING, message);
        ClassificationService classificationService = new ClassificationService(event.getGraphContext());
        classificationService.attachClassification(event, context, javaClassFileModel, UNPARSEABLE_CLASS_CLASSIFICATION, UNPARSEABLE_CLASS_DESCRIPTION);
        javaClassFileModel.setParseError(message);
        javaClassFileModel.setSkipDecompilation(true);
    }
}