Search in sources :

Example 1 with ClassParser

use of org.apache.bcel.classfile.ClassParser in project OpenGrok by OpenGrok.

the class JavaClassAnalyzer method analyze.

void analyze(Document doc, InputStream in, Writer xrefOut) throws IOException {
    List<String> defs = new ArrayList<>();
    List<String> refs = new ArrayList<>();
    List<String> full = new ArrayList<>();
    StringWriter dout = new StringWriter();
    StringWriter rout = new StringWriter();
    StringWriter fout = new StringWriter();
    /**
     * The JarAnalyzer uses JavaClassAnalyzer, so if a DEFS, REFS, or FULL
     * field exists already, then append to it.
     */
    useExtantValue(dout, doc, QueryBuilder.DEFS);
    useExtantValue(rout, doc, QueryBuilder.REFS);
    useExtantValue(fout, doc, QueryBuilder.FULL);
    ClassParser classparser = new ClassParser(in, doc.get(QueryBuilder.PATH));
    StringWriter xout = new StringWriter();
    getContent(xout, fout, classparser.parse(), defs, refs, full);
    String xref = xout.toString();
    if (xrefOut != null) {
        xrefOut.append(xref);
        try {
            xrefOut.flush();
        } catch (IOException ex) {
            LOGGER.log(Level.WARNING, "Couldn't flush xref, will retry once added to doc", ex);
        }
    }
    appendValues(dout, defs, "");
    appendValues(rout, refs, "");
    appendValues(fout, full, "// ");
    /**
     * Unlike other analyzers, which rely on the full content existing to be
     * accessed at a file system location identified by PATH, *.class and
     * *.jar files have virtual content which is stored here (Store.YES) for
     * analyzer convenience.
     */
    String dstr = dout.toString();
    doc.add(new TextField(QueryBuilder.DEFS, dstr, Store.YES));
    String rstr = rout.toString();
    doc.add(new TextField(QueryBuilder.REFS, rstr, Store.YES));
    String fstr = fout.toString();
    doc.add(new TextField(QueryBuilder.FULL, fstr, Store.YES));
}
Also used : StringWriter(java.io.StringWriter) ArrayList(java.util.ArrayList) TextField(org.apache.lucene.document.TextField) ConstantString(org.apache.bcel.classfile.ConstantString) IOException(java.io.IOException) ClassParser(org.apache.bcel.classfile.ClassParser)

Example 2 with ClassParser

use of org.apache.bcel.classfile.ClassParser in project ant by apache.

the class JavaClassHelper method getConstants.

/**
 * Get the constants declared in a file as name=value
 *
 * @param bytes the class as a array of bytes
 * @return a StringBuffer contains the name=value pairs
 * @exception IOException if an error occurs
 */
public static StringBuffer getConstants(final byte[] bytes) throws IOException {
    final StringBuffer sb = new StringBuffer();
    final ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    final ClassParser parser = new ClassParser(bis, "");
    final JavaClass javaClass = parser.parse();
    final Field[] fields = javaClass.getFields();
    for (final Field field : fields) {
        if (field != null) {
            final ConstantValue cv = field.getConstantValue();
            if (cv != null) {
                String cvs = cv.toString();
                // Remove start and end quotes if field is a String
                if (cvs.startsWith("\"") && cvs.endsWith("\"")) {
                    cvs = cvs.substring(1, cvs.length() - 1);
                }
                sb.append(field.getName());
                sb.append('=');
                sb.append(cvs);
                sb.append(LS);
            }
        }
    }
    return sb;
}
Also used : Field(org.apache.bcel.classfile.Field) JavaClass(org.apache.bcel.classfile.JavaClass) ByteArrayInputStream(java.io.ByteArrayInputStream) ConstantValue(org.apache.bcel.classfile.ConstantValue) ClassParser(org.apache.bcel.classfile.ClassParser)

Example 3 with ClassParser

use of org.apache.bcel.classfile.ClassParser in project tycho by eclipse.

the class OsgiCompilerTest method assertBytecodeMajorLevel.

private void assertBytecodeMajorLevel(int majorLevel, File classFile) throws ClassFormatException, IOException {
    assertTrue(classFile.canRead());
    JavaClass javaClass = new ClassParser(classFile.getAbsolutePath()).parse();
    assertEquals(majorLevel, javaClass.getMajor());
}
Also used : JavaClass(org.apache.bcel.classfile.JavaClass) ClassParser(org.apache.bcel.classfile.ClassParser)

Example 4 with ClassParser

use of org.apache.bcel.classfile.ClassParser in project jop by jop-devel.

the class AppInfo method tryLoadClass.

private ClassInfo tryLoadClass(String className) throws IOException {
    loadLogger.debug("Loading class " + className);
    InputStream is = classPath.getInputStream(className);
    JavaClass javaClass = new ClassParser(is, className).parse();
    is.close();
    if (javaClass.getMajor() > 50) {
        // instruction (requires patching of BCEL code similar to Classpath and InstructionFinder)
        throw new JavaClassFormatError("Classfiles with versions 51.0 (Java 7) and above are currently not supported!");
    }
    return new ClassInfo(new ClassGen(javaClass));
}
Also used : JavaClass(org.apache.bcel.classfile.JavaClass) InputStream(java.io.InputStream) JavaClassFormatError(com.jopdesign.common.misc.JavaClassFormatError) ClassGen(org.apache.bcel.generic.ClassGen) ClassParser(org.apache.bcel.classfile.ClassParser)

Example 5 with ClassParser

use of org.apache.bcel.classfile.ClassParser in project kanonizo by kanonizo.

the class Framework method loadClassFromFile.

private Class<?> loadClassFromFile(File file) {
    Class<?> cl = null;
    try {
        ClassParser parser = new ClassParser(file.getAbsolutePath());
        JavaClass jcl = parser.parse();
        List<String> forbiddenClasses = Arrays.asList(FORBIDDEN_CLASSNAMES.split(","));
        forbiddenClasses = forbiddenClasses.stream().filter(name -> !name.isEmpty()).collect(Collectors.toList());
        if (forbiddenClasses.size() > 0 && forbiddenClasses.stream().anyMatch(f -> jcl.getClassName().substring(jcl.getPackageName().length() + 1).startsWith(f))) {
            logger.info("Ignoring class " + jcl.getClassName() + " because it is forbidden");
            return null;
        } else {
            cl = Class.forName(jcl.getClassName(), true, Thread.currentThread().getContextClassLoader());
        }
    } catch (ClassNotFoundException | NoClassDefFoundError e) {
        logger.error(e);
    } catch (IOException e) {
        logger.error(e);
    } catch (ExceptionInInitializerError e) {
        logger.error(e);
    }
    return cl;
}
Also used : Arrays(java.util.Arrays) Reflections(org.reflections.Reflections) GsonBuilder(com.google.gson.GsonBuilder) TypeAdapter(com.google.gson.TypeAdapter) ClassUnderTest(org.kanonizo.framework.objects.ClassUnderTest) TestCase(org.kanonizo.framework.objects.TestCase) APLCFunction(org.kanonizo.algorithms.metaheuristics.fitness.APLCFunction) CoverageWriter(org.kanonizo.reporting.CoverageWriter) Gson(com.google.gson.Gson) Method(java.lang.reflect.Method) TestCaseSelectionListener(org.kanonizo.listeners.TestCaseSelectionListener) ParameterisedTestCase(org.kanonizo.framework.objects.ParameterisedTestCase) SearchAlgorithm(org.kanonizo.algorithms.SearchAlgorithm) TestingUtils(org.kanonizo.junit.TestingUtils) Expose(com.google.gson.annotations.Expose) Set(java.util.Set) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) Serializable(java.io.Serializable) InvocationTargetException(java.lang.reflect.InvocationTargetException) List(java.util.List) Util(org.kanonizo.util.Util) Logger(org.apache.logging.log4j.Logger) PropertyChangeListener(java.beans.PropertyChangeListener) Modifier(java.lang.reflect.Modifier) Optional(java.util.Optional) Display(org.kanonizo.display.Display) InstrumentedFitnessFunction(org.kanonizo.algorithms.metaheuristics.fitness.InstrumentedFitnessFunction) APBCFunction(org.kanonizo.algorithms.metaheuristics.fitness.APBCFunction) Parameters(org.junit.runners.Parameterized.Parameters) Parameter(com.scythe.instrumenter.InstrumentationProperties.Parameter) ClassParser(org.apache.bcel.classfile.ClassParser) JsonReader(com.google.gson.stream.JsonReader) APFDFunction(org.kanonizo.algorithms.metaheuristics.fitness.APFDFunction) ArrayList(java.util.ArrayList) CsvWriter(org.kanonizo.reporting.CsvWriter) Instrumenter(org.kanonizo.framework.instrumentation.Instrumenter) Prerequisite(org.kanonizo.annotations.Prerequisite) JsonWriter(com.google.gson.stream.JsonWriter) PropertyChangeEvent(java.beans.PropertyChangeEvent) MutationSearchAlgorithm(org.kanonizo.algorithms.MutationSearchAlgorithm) JavaClass(org.apache.bcel.classfile.JavaClass) FitnessFunction(org.kanonizo.algorithms.metaheuristics.fitness.FitnessFunction) MiscStatsWriter(org.kanonizo.reporting.MiscStatsWriter) Iterator(java.util.Iterator) NullInstrumenter(org.kanonizo.instrumenters.NullInstrumenter) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Algorithm(org.kanonizo.annotations.Algorithm) TestCaseOrderingWriter(org.kanonizo.reporting.TestCaseOrderingWriter) File(java.io.File) SystemUnderTest(org.kanonizo.framework.objects.SystemUnderTest) PropertyChangeSupport(java.beans.PropertyChangeSupport) FileReader(java.io.FileReader) NullDisplay(org.kanonizo.display.NullDisplay) Comparator(java.util.Comparator) LogManager(org.apache.logging.log4j.LogManager) JavaClass(org.apache.bcel.classfile.JavaClass) IOException(java.io.IOException) ClassParser(org.apache.bcel.classfile.ClassParser)

Aggregations

ClassParser (org.apache.bcel.classfile.ClassParser)13 JavaClass (org.apache.bcel.classfile.JavaClass)10 IOException (java.io.IOException)7 File (java.io.File)4 HashSet (java.util.HashSet)4 InputStream (java.io.InputStream)3 ArrayList (java.util.ArrayList)3 StringWriter (java.io.StringWriter)2 Set (java.util.Set)2 ZipEntry (java.util.zip.ZipEntry)2 Gson (com.google.gson.Gson)1 GsonBuilder (com.google.gson.GsonBuilder)1 TypeAdapter (com.google.gson.TypeAdapter)1 Expose (com.google.gson.annotations.Expose)1 JsonReader (com.google.gson.stream.JsonReader)1 JsonWriter (com.google.gson.stream.JsonWriter)1 JavaClassFormatError (com.jopdesign.common.misc.JavaClassFormatError)1 Parameter (com.scythe.instrumenter.InstrumentationProperties.Parameter)1 BugInstance (edu.umd.cs.findbugs.BugInstance)1 PropertyChangeEvent (java.beans.PropertyChangeEvent)1