<commit_before>package tests;

import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import de.tobject.findbugs.FindbugsPlugin;
import de.tobject.findbugs.builder.FindBugsWorker;
import de.tobject.findbugs.builder.WorkItem;
import de.tobject.findbugs.reporter.MarkerUtil;

import edu.umd.cs.findbugs.DetectorFactory;
import edu.umd.cs.findbugs.DetectorFactoryCollection;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import edu.umd.cs.findbugs.plugin.eclipse.quickfix.BugResolutionGenerator;

import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.ui.IMarkerResolution;
import org.eclipse.ui.PartInitException;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import quickfix.DeadShadowStoreResolution;
import quickfix.InsecureRandomResolution;
import quickfix.ReturnValueIgnoreResolution;
import utils.BugResolutionSource;
import utils.QuickFixTestPackage;
import utils.QuickFixTestPackager;
import utils.TestingUtils;

@RunWith(JUnit4.class)
public class TestContributedQuickFixes {

    public final static String PROJECT_NAME = "fb-contrib-test-quick-fixes";

    public final static String BIN_FOLDER_NAME = "bin";

    public final static String SRC_FOLDER_NAME = "src";

    private static IJavaProject testProject;

    private static IProject testIProject;

    private BugResolutionSource resolutionSource;
    
    @Rule
    @SuppressFBWarnings(value="URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD", justification="This is what the sample code does.")
    public TestWatcher watcher = new TestWatcher() {
        @Override
        protected void failed(Throwable e, Description description) {
            System.out.println("Failed");
            //TestingUtils.waitForUiEvents(20_000);
        }

        @Override
        protected void succeeded(Description description) {
            System.out.println("Passed");
           }
       };

    @BeforeClass
    public static void loadFilesThatNeedFixing() throws CoreException, IOException {
        makeJavaProject();

        TestingUtils.copyBrokenFiles(new File("classesToFix/"), testIProject.getFolder(SRC_FOLDER_NAME));

        // Compiles the code
        testIProject.refreshLocal(IResource.DEPTH_INFINITE, null);
        testIProject.build(IncrementalProjectBuilder.FULL_BUILD, null);

        FindbugsPlugin.setProjectSettingsEnabled(testIProject, null, true);
        
        TestingUtils.waitForUiEvents(100);
    }

    private static void clearMarkersAndBugs() throws CoreException {
        MarkerUtil.removeMarkers(testIProject);
        FindbugsPlugin.getBugCollection(testIProject, null, false).clearBugInstances();
    }

    private static void makeJavaProject() throws CoreException {
        testProject = JavaProjectHelper.createJavaProject(PROJECT_NAME, BIN_FOLDER_NAME);
        JavaProjectHelper.addRTJar17(testProject);
        JavaProjectHelper.addSourceContainer(testProject, SRC_FOLDER_NAME);
        testProject.setOption("org.eclipse.jdt.core.formatter.tabulation.char", JavaCore.SPACE);
        testIProject = testProject.getProject();
    }

    @Before
    public void setup() {
        final BugResolutionGenerator resolutionGenerator = new BugResolutionGenerator();
        // we wrap this in case the underlying generator interface changes.
        resolutionSource = new BugResolutionSource() {
            @Override
            public IMarkerResolution[] getResolutions(IMarker marker) {
                return resolutionGenerator.getResolutions(marker);
            }

            @Override
            public boolean hasResolutions(IMarker marker) {
                return resolutionGenerator.hasResolutions(marker);
            }
        };
    }

    private void checkBugsAndPerformResolution(List<QuickFixTestPackage> packages, String testResource) {
        try {
            showEditorWindowForFile(testResource);
            scanForBugs(testResource);
            assertBugPatternsMatch(packages, testResource);
            executeResolutions(packages, testResource);
            assertOutputAndInputFilesMatch(testResource);
        } catch (CoreException | IOException e) {
            e.printStackTrace();
            fail("Exception thrown while performing resolution on " + testResource);
        }

    }

    private void showEditorWindowForFile(String testResource) throws JavaModelException, PartInitException {
        JavaUI.openInEditor(TestingUtils.elementFromProject(testProject, testResource), true, true);
    }

    /**
     * Blocks until FindBugs has finished scanning
     * 
     * @param className
     *            file in this project to scan
     * @throws CoreException
     */
    private void scanForBugs(String className) throws CoreException {
        IJavaElement element = testProject.findElement(new Path(className));
        if (element == null)
        {
            fail("Could not find java class " + className);
            return;
        }
        final AtomicBoolean isWorking = new AtomicBoolean(true);
        FindBugsWorker worker = new FindBugsWorker(testProject.getProject(), new NullProgressMonitor() {
            @Override
            public void done() {
                isWorking.set(false);
            }
        });

        worker.work(Collections.singletonList(new WorkItem(element)));
        // wait for the findBugsWorker to finish
        // 500ms reduces the chance that the IMarkers haven't loaded yet and the tests will fail unpredictably
        // (see JavaProjectHelper discussion about performDummySearch for more info)
        TestingUtils.waitForUiEvents(500);
        while (isWorking.get()) {
            TestingUtils.waitForUiEvents(100);
        }
    }
<commit_msg>Trying slightly longer UI waits<commit_after>package tests;

import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import de.tobject.findbugs.FindbugsPlugin;
import de.tobject.findbugs.builder.FindBugsWorker;
import de.tobject.findbugs.builder.WorkItem;
import de.tobject.findbugs.reporter.MarkerUtil;

import edu.umd.cs.findbugs.DetectorFactory;
import edu.umd.cs.findbugs.DetectorFactoryCollection;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import edu.umd.cs.findbugs.plugin.eclipse.quickfix.BugResolutionGenerator;

import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.ui.IMarkerResolution;
import org.eclipse.ui.PartInitException;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import quickfix.DeadShadowStoreResolution;
import quickfix.InsecureRandomResolution;
import quickfix.ReturnValueIgnoreResolution;
import utils.BugResolutionSource;
import utils.QuickFixTestPackage;
import utils.QuickFixTestPackager;
import utils.TestingUtils;

@RunWith(JUnit4.class)
public class TestContributedQuickFixes {

    public final static String PROJECT_NAME = "fb-contrib-test-quick-fixes";

    public final static String BIN_FOLDER_NAME = "bin";

    public final static String SRC_FOLDER_NAME = "src";

    private static IJavaProject testProject;

    private static IProject testIProject;

    private BugResolutionSource resolutionSource;
    
    @Rule
    @SuppressFBWarnings(value="URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD", justification="This is what the sample code does.")
    public TestWatcher watcher = new TestWatcher() {
        @Override
        protected void failed(Throwable e, Description description) {
            System.out.println("Failed");
            //TestingUtils.waitForUiEvents(20_000);
        }

        @Override
        protected void succeeded(Description description) {
            System.out.println("Passed");
           }
       };

    @BeforeClass
    public static void loadFilesThatNeedFixing() throws CoreException, IOException {
        makeJavaProject();

        TestingUtils.copyBrokenFiles(new File("classesToFix/"), testIProject.getFolder(SRC_FOLDER_NAME));

        // Compiles the code
        testIProject.refreshLocal(IResource.DEPTH_INFINITE, null);
        testIProject.build(IncrementalProjectBuilder.FULL_BUILD, null);

        FindbugsPlugin.setProjectSettingsEnabled(testIProject, null, true);
        
        TestingUtils.waitForUiEvents(100);
    }

    private static void clearMarkersAndBugs() throws CoreException {
        MarkerUtil.removeMarkers(testIProject);
        FindbugsPlugin.getBugCollection(testIProject, null, false).clearBugInstances();
    }

    private static void makeJavaProject() throws CoreException {
        testProject = JavaProjectHelper.createJavaProject(PROJECT_NAME, BIN_FOLDER_NAME);
        JavaProjectHelper.addRTJar17(testProject);
        JavaProjectHelper.addSourceContainer(testProject, SRC_FOLDER_NAME);
        testProject.setOption("org.eclipse.jdt.core.formatter.tabulation.char", JavaCore.SPACE);
        testIProject = testProject.getProject();
    }

    @Before
    public void setup() {
        final BugResolutionGenerator resolutionGenerator = new BugResolutionGenerator();
        // we wrap this in case the underlying generator interface changes.
        resolutionSource = new BugResolutionSource() {
            @Override
            public IMarkerResolution[] getResolutions(IMarker marker) {
                return resolutionGenerator.getResolutions(marker);
            }

            @Override
            public boolean hasResolutions(IMarker marker) {
                return resolutionGenerator.hasResolutions(marker);
            }
        };
    }

    private void checkBugsAndPerformResolution(List<QuickFixTestPackage> packages, String testResource) {
        try {
            showEditorWindowForFile(testResource);
            scanForBugs(testResource);
            assertBugPatternsMatch(packages, testResource);
            executeResolutions(packages, testResource);
            assertOutputAndInputFilesMatch(testResource);
        } catch (CoreException | IOException e) {
            e.printStackTrace();
            fail("Exception thrown while performing resolution on " + testResource);
        }

    }

    private void showEditorWindowForFile(String testResource) throws JavaModelException, PartInitException {
        JavaUI.openInEditor(TestingUtils.elementFromProject(testProject, testResource), true, true);
    }

    /**
     * Blocks until FindBugs has finished scanning
     * 
     * @param className
     *            file in this project to scan
     * @throws CoreException
     */
    private void scanForBugs(String className) throws CoreException {
        IJavaElement element = testProject.findElement(new Path(className));
        if (element == null)
        {
            fail("Could not find java class " + className);
            return;
        }
        final AtomicBoolean isWorking = new AtomicBoolean(true);
        FindBugsWorker worker = new FindBugsWorker(testProject.getProject(), new NullProgressMonitor() {
            @Override
            public void done() {
                isWorking.set(false);
            }
        });

        worker.work(Collections.singletonList(new WorkItem(element)));
        // wait for the findBugsWorker to finish
        // 500ms reduces the chance that the IMarkers haven't loaded yet and the tests will fail unpredictably
        // (see JavaProjectHelper discussion about performDummySearch for more info)
        TestingUtils.waitForUiEvents(800);
        while (isWorking.get()) {
            TestingUtils.waitForUiEvents(100);
        }
    }

{'fraction_non_alphanumeric': 0.083447959651536, 'fraction_numerical': 0.0032095369096744614, 'mean_word_length': 3.4317643074839146, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2260997', 'n_tokens_mistral': 3625, 'n_tokens_neox': 3477, 'n_words': 730}