如何使用 Spoon 从 java Class 中删除评论?

How to remove Comments from a java Class using Spoon?

我正在使用 SequenceR 来解析我的 Java 代码文件。它使用 Java 的 Spoon 库,这是一个流行的代码分析库。我需要的是,我会给分析器一个有问题的行号,它会检测该行并找出它的方法或 class,它会删除所有关于 class 或方法的注释.

我尝试了多种方法来实现这一目标。但无法真正获得所需的输出。

这是我的输入 Java 文件。


public class CWE23_Relative_Path_Traversal__connect_tcp_01 extends AbstractTestCase
{
    /* uses badsource and badsink */
    public void bad() throws Throwable
    {
        String data;

        data = ""; /* Initialize data */

        /* Read data using an outbound tcp connection */
        {
            Socket socket = null;
            BufferedReader readerBuffered = null;
            InputStreamReader readerInputStream = null;

            try
            {
                /* Read data using an outbound tcp connection */
                socket = new Socket("host.example.org", 39544);

                /* read input from socket */

                readerInputStream = new InputStreamReader(socket.getInputStream(), "UTF-8");
                readerBuffered = new BufferedReader(readerInputStream);

                /* POTENTIAL FLAW: Read data using an outbound tcp connection */
                data = readerBuffered.readLine();
            }
            catch (IOException exceptIO)
            {
                IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
            }
            finally
            {
                /* clean up stream reading objects */
                try
                {
                    if (readerBuffered != null)
                    {
                        readerBuffered.close();
                    }
                }
                catch (IOException exceptIO)
                {
                    IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
                }

                try
                {
                    if (readerInputStream != null)
                    {
                        readerInputStream.close();
                    }
                }
                catch (IOException exceptIO)
                {
                    IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
                }

                /* clean up socket objects */
                try
                {
                    if (socket != null)
                    {
                        socket.close();
                    }
                }
                catch (IOException exceptIO)
                {
                    IO.logger.log(Level.WARNING, "Error closing Socket", exceptIO);
                }
            }
        }

        String root;
        if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)
        {
            /* running on Windows */
            root = "C:\uploads\";
        }
        else
        {
            /* running on non-Windows */
            root = "/home/user/uploads/";
        }

        if (data != null)
        {
            /* POTENTIAL FLAW: no validation of concatenated value */
            File file = new File(root + data);
            FileInputStream streamFileInputSink = null;
            InputStreamReader readerInputStreamSink = null;
            BufferedReader readerBufferdSink = null;
            if (file.exists() && file.isFile())
            {
                try
                {
                    streamFileInputSink = new FileInputStream(file);
                    readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
                    readerBufferdSink = new BufferedReader(readerInputStreamSink);
                    IO.writeLine(readerBufferdSink.readLine());
                }
                catch (IOException exceptIO)
                {
                    IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
                }
                finally
                {
                    /* Close stream reading objects */
                    try
                    {
                        if (readerBufferdSink != null)
                        {
                            readerBufferdSink.close();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
                    }

                    try
                    {
                        if (readerInputStreamSink != null)
                        {
                            readerInputStreamSink.close();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
                    }

                    try
                    {
                        if (streamFileInputSink != null)
                        {
                            streamFileInputSink.close();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
                    }
                }
            }
        }

    }

    public void good() throws Throwable
    {
        goodG2B();
    }

    /* goodG2B() - uses goodsource and badsink */
    private void goodG2B() throws Throwable
    {
        String data;

        /* FIX: Use a hardcoded string */
        data = "foo";

        String root;
        if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)
        {
            /* running on Windows */
            root = "C:\uploads\";
        }
        else
        {
            /* running on non-Windows */
            root = "/home/user/uploads/";
        }

        if (data != null)
        {
            /* POTENTIAL FLAW: no validation of concatenated value */
            File file = new File(root + data);
            FileInputStream streamFileInputSink = null;
            InputStreamReader readerInputStreamSink = null;
            BufferedReader readerBufferdSink = null;
            if (file.exists() && file.isFile())
            {
                try
                {
                    streamFileInputSink = new FileInputStream(file);
                    readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
                    readerBufferdSink = new BufferedReader(readerInputStreamSink);
                    IO.writeLine(readerBufferdSink.readLine());
                }
                catch (IOException exceptIO)
                {
                    IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
                }
                finally
                {
                    /* Close stream reading objects */
                    try
                    {
                        if (readerBufferdSink != null)
                        {
                            readerBufferdSink.close();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
                    }

                    try
                    {
                        if (readerInputStreamSink != null)
                        {
                            readerInputStreamSink.close();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
                    }

                    try
                    {
                        if (streamFileInputSink != null)
                        {
                            streamFileInputSink.close();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
                    }
                }
            }
        }

    }

    /* Below is the main(). It is only used when building this testcase on
     * its own for testing or for building a binary to use in testing binary
     * analysis tools. It is not used when compiling all the testcases as one
     * application, which is how source code analysis tools are tested.
     */
    public static void main(String[] args) throws ClassNotFoundException,
           InstantiationException, IllegalAccessException
    {
        mainFromParent(args);
    }
}

我在分析器代码中所做的是这样的 -


    public static void generateAbstraction(File buggy_file, int buggy_line, File working_dir) {
        Launcher launcher = new Launcher();
        launcher.getEnvironment().setAutoImports(true);
        launcher.getEnvironment().setNoClasspath(true);
        launcher.getEnvironment().setCommentEnabled(true);
        launcher.addInputResource(buggy_file.toString());
        try {
            launcher.buildModel();
        } catch (Exception e) {

        }

        CtModel model = launcher.getModel();

        CtMethod topLevelmethod = null;
        CtElement buggy_ctElement = null;
        CtElement tmp_ctElement = null;
        CtPath buggy_ctElement_ctPath = null;


        // This is the main part

        for (CtType<?> ctType : model.getAllTypes()) {

            for (Iterator<CtElement> desIter = ctType.descendantIterator(); desIter.hasNext(); ) {
                tmp_ctElement = desIter.next();

                try {

                    // Main problem resides here

                    if (tmp_ctElement.getPosition().getLine() == buggy_line && !(tmp_ctElement instanceof CtComment)) {
                        buggy_ctElement = tmp_ctElement;
                        buggy_ctElement_ctPath = tmp_ctElement.getPath();

                        topLevelmethod = getTopLevelMethod(buggy_ctElement);

                        List<CtComment> comments = topLevelmethod.getElements(
                                new TypeFilter<CtComment>(CtComment.class)
                        );

                        for(CtComment c: comments){
                               topLevelmethod.removeComment(c);
                        }

                        break;
                    }
                } catch (java.lang.UnsupportedOperationException e) {
                    continue;
                }
            }

            // ......
        }

    }

    public static CtMethod getTopLevelMethod(CtElement ctElement) {
        CtMethod topLevelMethod = null;
        topLevelMethod = ctElement.getParent(CtMethod.class);
        while (topLevelMethod != null && topLevelMethod.getParent(CtMethod.class) != null) {
            System.out.println();
            topLevelMethod = topLevelMethod.getParent(CtMethod.class);
        }
        return topLevelMethod;
    }

输出是这样的 -

public class CWE23_Relative_Path_Traversal__connect_tcp_01 extends AbstractTestCase {
    public void bad() throws Throwable {
        String data;
        data = "";/* Initialize data */

        /* Read data using an outbound tcp connection */
        {
            Socket socket = null;
            BufferedReader readerBuffered = null;
            InputStreamReader readerInputStream = null;
            try {
                /* Read data using an outbound tcp connection */
                socket = new Socket("host.example.org", 39544);
                /* read input from socket */
                readerInputStream = new InputStreamReader(socket.getInputStream(), "UTF-8");
                readerBuffered = new BufferedReader(readerInputStream);
                /* POTENTIAL FLAW: Read data using an outbound tcp connection */
                data = readerBuffered.readLine();
            } catch (IOException exceptIO) {
                logger.log(Level.WARNING, "Error with stream reading", exceptIO);
            } finally {
                /* clean up stream reading objects */
                try {
                    if (readerBuffered != null) {
                        readerBuffered.close();
                    }
                } catch (IOException exceptIO) {
                    logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
                }
                try {
                    if (readerInputStream != null) {
                        readerInputStream.close();
                    }
                } catch (IOException exceptIO) {
                    logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
                }
                /* clean up socket objects */
                try {
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException exceptIO) {
                    logger.log(Level.WARNING, "Error closing Socket", exceptIO);
                }
            }
        }
        String root;
        if ((System.getProperty("os.name").toLowerCase().indexOf("win")) >= 0) {
            /* running on Windows */
            root = "C:\uploads\";
        }else {
            /* running on non-Windows */
            root = "/home/user/uploads/";
        }
        if (data != null) {
            /* POTENTIAL FLAW: no validation of concatenated value */
            File file = new File((root + data));
            FileInputStream streamFileInputSink = null;
            InputStreamReader readerInputStreamSink = null;
            BufferedReader readerBufferdSink = null;
            if ((file.exists()) && (file.isFile())) {
                try {
                    streamFileInputSink = new FileInputStream(file);
                    readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
                    readerBufferdSink = new BufferedReader(readerInputStreamSink);
                    IO.writeLine(readerBufferdSink.readLine());
                } catch (IOException exceptIO) {
                    logger.log(Level.WARNING, "Error with stream reading", exceptIO);
                } finally {
                    /* Close stream reading objects */
                    try {
                        if (readerBufferdSink != null) {
                            readerBufferdSink.close();
                        }
                    } catch (IOException exceptIO) {
                        logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
                    }
                    try {
                        if (readerInputStreamSink != null) {
                            readerInputStreamSink.close();
                        }
                    } catch (IOException exceptIO) {
                        logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
                    }
                    try {
                        if (streamFileInputSink != null) {
                            streamFileInputSink.close();
                        }
                    } catch (IOException exceptIO) {
                        logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
                    }
                }
            }
        }
    }

    public void good() throws Throwable {
    }

    /* goodG2B() - uses goodsource and badsink */
    private void goodG2B() throws Throwable {
    }

    /* Below is the main(). It is only used when building this testcase on
    its own for testing or for building a binary to use in testing binary
    analysis tools. It is not used when compiling all the testcases as one
    application, which is how source code analysis tools are tested.
     */
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    }
}

如果你仔细看,你会发现只有一条评论被删除了。那就是 -

/* uses badsource and badsink */

其他评论完好无损。但是我需要删除 class 或方法中的所有注释。我究竟做错了什么?我对勺子完全陌生。任何帮助将不胜感激。

几分钟前我无意中找到了答案。我不会删除这个答案,因为有人可能会觉得这很有用。 要删除文件的所有评论,您只需要关闭一个标志。

这条线很神奇 -

launcher.getEnvironment().setCommentEnabled(false);

它的作用是设置 setCommentEnabledfalse 并完全忽略评论。所以,你根本不需要担心它们。这个简单的解决方案花了我 6 个小时才弄明白。