Skip to content

Commit 45f8040

Browse files
committed
Merge pull request #146 from adangel:refactor-actions
Refactor actions to use correct selection #146
2 parents a29549d + 3b0b9ae commit 45f8040

File tree

15 files changed

+305
-301
lines changed

15 files changed

+305
-301
lines changed

ReleaseNotes.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ This is a minor release.
1515

1616
### Fixed Issues
1717

18+
* [#146](https://github.com/pmd/pmd-eclipse-plugin/pull/146): Refactor actions to use correct selection
19+
1820
### API Changes
1921

2022
### External Contributions

net.sourceforge.pmd.eclipse.plugin.test.fragment/src/main/resources/rulesets/extra1.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ Override both public boolean Object.equals(Object other), and public int Object.
273273
<![CDATA[
274274
//ClassOrInterfaceDeclaration[@Interface='false']//MethodDeclarator
275275
[(@Image = 'equals' and count(FormalParameters/*) = 1
276-
and not(//MethodDeclarator[count(FormalParameters/*) = 0][@Image = 'hashCode']))
276+
and not(//MethodDeclarator[count(FormalParameters/*) = 0][@Name = 'hashCode']))
277277
or
278278
(@Image='hashCode' and count(FormalParameters/*) = 0
279279
and

net.sourceforge.pmd.eclipse.plugin.test/pom.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
<artifactId>tycho-surefire-plugin</artifactId>
2525
<configuration>
2626
<useUIHarness>true</useUIHarness>
27+
<useUIThread>false</useUIThread>
2728
<showEclipseLog>true</showEclipseLog>
2829
<trimStackTrace>false</trimStackTrace>
2930
<!-- http://wiki.eclipse.org/Eclipse4/RCP/FAQ#Why_won.27t_my_application_start.3F -->

net.sourceforge.pmd.eclipse.plugin.test/src/main/java/net/sourceforge/pmd/eclipse/BasicPMDTest.java

Lines changed: 13 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -5,30 +5,24 @@
55
package net.sourceforge.pmd.eclipse;
66

77
import java.io.ByteArrayInputStream;
8-
import java.io.File;
98
import java.io.IOException;
109
import java.io.InputStream;
11-
import java.io.UnsupportedEncodingException;
10+
import java.nio.charset.StandardCharsets;
1211
import java.util.ArrayList;
1312
import java.util.Collections;
14-
import java.util.Iterator;
1513
import java.util.List;
1614

1715
import org.junit.Assert;
1816
import org.junit.Test;
1917

2018
import net.sourceforge.pmd.PMD;
2119
import net.sourceforge.pmd.PMDConfiguration;
22-
import net.sourceforge.pmd.RuleContext;
20+
import net.sourceforge.pmd.Report;
2321
import net.sourceforge.pmd.RuleSet;
24-
import net.sourceforge.pmd.RuleSetFactory;
25-
import net.sourceforge.pmd.RuleSetNotFoundException;
22+
import net.sourceforge.pmd.RuleSetLoader;
2623
import net.sourceforge.pmd.RuleViolation;
27-
import net.sourceforge.pmd.RulesetsFactoryUtils;
28-
import net.sourceforge.pmd.ThreadSafeReportListener;
2924
import net.sourceforge.pmd.lang.LanguageRegistry;
3025
import net.sourceforge.pmd.renderers.Renderer;
31-
import net.sourceforge.pmd.stat.Metric;
3226
import net.sourceforge.pmd.util.datasource.DataSource;
3327

3428
/**
@@ -43,11 +37,7 @@ static class StringDataSource implements DataSource {
4337
private final ByteArrayInputStream is;
4438

4539
StringDataSource(final String source) {
46-
try {
47-
this.is = new ByteArrayInputStream(source.getBytes("UTF-8"));
48-
} catch (UnsupportedEncodingException e) {
49-
throw new RuntimeException(e);
50-
}
40+
this.is = new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
5141
}
5242

5343
@Override
@@ -72,49 +62,29 @@ public void close() throws IOException {
7262
*/
7363
@Test
7464
public void testDefaulltRuleSets() {
75-
try {
76-
final RuleSetFactory factory = RulesetsFactoryUtils.defaultFactory();
77-
final Iterator<RuleSet> iterator = factory.getRegisteredRuleSets();
78-
while (iterator.hasNext()) {
79-
iterator.next();
80-
}
81-
} catch (final RuleSetNotFoundException e) {
82-
e.printStackTrace();
83-
Assert.fail("unable to load registered rulesets ");
84-
}
65+
RuleSetLoader rulesetloader = new RuleSetLoader();
66+
List<RuleSet> standardRuleSets = rulesetloader.getStandardRuleSets();
67+
Assert.assertFalse("No Rulesets found", standardRuleSets.isEmpty());
8568
}
8669

8770
private void runPmd(String javaVersion) {
8871
PMDConfiguration configuration = new PMDConfiguration();
8972
configuration.setDefaultLanguageVersion(LanguageRegistry.findLanguageByTerseName("java").getVersion(javaVersion));
9073
configuration.setRuleSets("category/java/codestyle.xml/UnnecessaryReturn");
91-
RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.createFactory(configuration);
74+
configuration.setIgnoreIncrementalAnalysis(true);
75+
RuleSetLoader rulesetLoader = RuleSetLoader.fromPmdConfig(configuration);
76+
List<RuleSet> rulesets = rulesetLoader.loadFromResources(configuration.getRuleSets());
9277

9378
List<DataSource> files = new ArrayList<>();
9479
final String sourceCode = "public class Foo {\n public void foo() {\nreturn;\n}}";
9580
files.add(new StringDataSource(sourceCode));
9681

97-
final List<RuleViolation> violations = new ArrayList<>();
98-
final RuleContext ctx = new RuleContext();
99-
ctx.setSourceCodeFile(new File("foo.java"));
100-
ctx.getReport().addListener(new ThreadSafeReportListener() {
101-
@Override
102-
public void ruleViolationAdded(RuleViolation ruleViolation) {
103-
violations.add(ruleViolation);
104-
}
105-
106-
@Override
107-
public void metricAdded(Metric metric) {
108-
}
109-
});
110-
111-
112-
PMD.processFiles(configuration, ruleSetFactory, files, ctx,
82+
Report result = PMD.processFiles(configuration, rulesets, files,
11383
Collections.<Renderer>emptyList());
11484

115-
Assert.assertFalse("There should be at least one violation", violations.isEmpty());
85+
Assert.assertFalse("There should be at least one violation", result.getViolations().isEmpty());
11686

117-
final RuleViolation violation = violations.get(0);
87+
final RuleViolation violation = result.getViolations().get(0);
11888
Assert.assertEquals(violation.getRule().getName(), "UnnecessaryReturn");
11989
Assert.assertEquals(3, violation.getBeginLine());
12090
}
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/*
2+
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3+
*/
4+
5+
package net.sourceforge.pmd.eclipse.ui.actions;
6+
7+
import java.io.InputStream;
8+
9+
import org.eclipse.core.resources.IMarker;
10+
import org.eclipse.core.resources.IProject;
11+
import org.eclipse.core.resources.IResource;
12+
import org.eclipse.core.resources.WorkspaceJob;
13+
import org.eclipse.core.runtime.CoreException;
14+
import org.eclipse.core.runtime.jobs.Job;
15+
import org.eclipse.jface.viewers.ISelection;
16+
import org.eclipse.jface.viewers.StructuredSelection;
17+
import org.eclipse.swt.widgets.Display;
18+
import org.junit.After;
19+
import org.junit.Assert;
20+
import org.junit.Before;
21+
import org.junit.Test;
22+
23+
import net.sourceforge.pmd.eclipse.EclipseUtils;
24+
import net.sourceforge.pmd.eclipse.plugin.PMDPlugin;
25+
import net.sourceforge.pmd.eclipse.runtime.properties.IProjectProperties;
26+
27+
public class PMDCheckActionTest {
28+
private IProject testProject;
29+
30+
@Before
31+
public void setUp() throws Exception {
32+
// 1. Create a Java project
33+
this.testProject = EclipseUtils.createJavaProject("PMDCheckActionTest");
34+
Assert.assertTrue("A test project cannot be created; the tests cannot be performed.",
35+
this.testProject != null && this.testProject.exists() && this.testProject.isAccessible());
36+
37+
// 2. Create a test source file inside that project
38+
EclipseUtils.createTestSourceFile(this.testProject);
39+
final InputStream is = EclipseUtils.getResourceStream(this.testProject, "/src/Test.java");
40+
Assert.assertNotNull("Cannot find the test source file", is);
41+
is.close();
42+
43+
// 3. Enable PMD for the test project
44+
IProjectProperties properties = PMDPlugin.getDefault().getPropertiesManager()
45+
.loadProjectProperties(testProject);
46+
properties.setPmdEnabled(true);
47+
}
48+
49+
@After
50+
public void tearDown() throws Exception {
51+
try {
52+
if (this.testProject != null) {
53+
if (this.testProject.exists() && this.testProject.isAccessible()) {
54+
EclipseUtils.removePMDNature(this.testProject);
55+
this.testProject.refreshLocal(IResource.DEPTH_INFINITE, null);
56+
this.testProject.delete(true, true, null);
57+
this.testProject = null;
58+
}
59+
}
60+
} catch (final Exception e) {
61+
System.out.println("Exception " + e.getClass().getName() + " when tearing down. Ignored.");
62+
}
63+
}
64+
65+
@Test
66+
public void runCheckAction() throws CoreException, InterruptedException {
67+
IMarker[] markers = testProject.findMarkers("net.sourceforge.pmd.eclipse.plugin.pmdMarker", true, IResource.DEPTH_INFINITE);
68+
Assert.assertEquals(0, markers.length);
69+
70+
Display.getDefault().syncExec(new Runnable() {
71+
@Override
72+
public void run() {
73+
ISelection selection = new StructuredSelection(testProject);
74+
PMDCheckAction action = new PMDCheckAction();
75+
action.selectionChanged(null, selection);
76+
action.run(null);
77+
}
78+
});
79+
80+
while (isReviewCodeJobStillRunning()) {
81+
Thread.sleep(500);
82+
}
83+
84+
markers = testProject.findMarkers("net.sourceforge.pmd.eclipse.plugin.pmdMarker", true, IResource.DEPTH_INFINITE);
85+
Assert.assertTrue("at least one marker is expected", markers.length > 0);
86+
}
87+
88+
private boolean isReviewCodeJobStillRunning() {
89+
Job[] jobs = WorkspaceJob.getJobManager().find(null);
90+
for (Job job : jobs) {
91+
if ("ReviewCode".equals(job.getName())) {
92+
return true;
93+
}
94+
}
95+
return false;
96+
}
97+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/*
2+
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3+
*/
4+
5+
package net.sourceforge.pmd.eclipse.ui.actions;
6+
7+
import java.io.IOException;
8+
import java.io.InputStream;
9+
10+
import org.apache.commons.io.FilenameUtils;
11+
import org.apache.commons.io.IOUtils;
12+
import org.eclipse.core.resources.IFile;
13+
import org.eclipse.core.resources.IProject;
14+
import org.eclipse.core.resources.IResource;
15+
import org.eclipse.core.runtime.CoreException;
16+
import org.eclipse.jface.action.IAction;
17+
import org.eclipse.jface.viewers.ISelection;
18+
import org.eclipse.jface.viewers.StructuredSelection;
19+
import org.eclipse.swt.widgets.Display;
20+
import org.junit.After;
21+
import org.junit.Assert;
22+
import org.junit.Before;
23+
import org.junit.Test;
24+
25+
import net.sourceforge.pmd.eclipse.EclipseUtils;
26+
import net.sourceforge.pmd.eclipse.plugin.PMDPlugin;
27+
import net.sourceforge.pmd.eclipse.runtime.properties.IProjectProperties;
28+
29+
public class PMDGenerateASTActionTest {
30+
private IProject testProject;
31+
private IFile testFile;
32+
33+
@Before
34+
public void setUp() throws Exception {
35+
// 1. Create a Java project
36+
this.testProject = EclipseUtils.createJavaProject("PMDGenerateASTActionTest");
37+
Assert.assertTrue("A test project cannot be created; the tests cannot be performed.",
38+
this.testProject != null && this.testProject.exists() && this.testProject.isAccessible());
39+
40+
// 2. Create a test source file inside that project
41+
this.testFile = EclipseUtils.createTestSourceFile(this.testProject);
42+
final InputStream is = EclipseUtils.getResourceStream(this.testProject, "/src/Test.java");
43+
Assert.assertNotNull("Cannot find the test source file", is);
44+
is.close();
45+
46+
// 3. Enable PMD for the test project
47+
IProjectProperties properties = PMDPlugin.getDefault().getPropertiesManager()
48+
.loadProjectProperties(testProject);
49+
properties.setPmdEnabled(true);
50+
}
51+
52+
@After
53+
public void tearDown() throws Exception {
54+
try {
55+
if (this.testProject != null) {
56+
if (this.testProject.exists() && this.testProject.isAccessible()) {
57+
EclipseUtils.removePMDNature(this.testProject);
58+
this.testProject.refreshLocal(IResource.DEPTH_INFINITE, null);
59+
this.testProject.delete(true, true, null);
60+
this.testProject = null;
61+
}
62+
}
63+
} catch (final Exception e) {
64+
System.out.println("Exception " + e.getClass().getName() + " when tearing down. Ignored.");
65+
}
66+
}
67+
68+
@Test
69+
public void runGenerateASTAction() throws CoreException, InterruptedException, IOException {
70+
Display.getDefault().syncExec(new Runnable() {
71+
@Override
72+
public void run() {
73+
ISelection selection = new StructuredSelection(testFile);
74+
PMDGenerateASTAction action = new PMDGenerateASTAction();
75+
action.selectionChanged(null, selection);
76+
action.run((IAction) null);
77+
}
78+
});
79+
80+
String astFilename = FilenameUtils.getBaseName(testFile.getName()) + ".ast";
81+
IResource astFile;
82+
long start = System.currentTimeMillis();
83+
do {
84+
Thread.sleep(500);
85+
astFile = testFile.getParent().findMember(astFilename);
86+
} while (astFile == null || (System.currentTimeMillis() - start) > 60_000);
87+
88+
Assert.assertNotNull("No AST file has been generated", astFile);
89+
IFile adapter = (IFile) astFile.getAdapter(IFile.class);
90+
String content = IOUtils.toString(adapter.getContents(), adapter.getCharset());
91+
Assert.assertTrue(content.startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
92+
Assert.assertTrue(content.contains("<CompilationUnit"));
93+
}
94+
}

net.sourceforge.pmd.eclipse.plugin/src/main/java/net/sourceforge/pmd/eclipse/runtime/cmd/BaseVisitor.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,9 @@ protected final void reviewResource(IResource resource) {
316316
configuration().setClassLoader(projectProperties.getAuxClasspath());
317317
}
318318

319+
// Avoid warnings about not providing cache for incremental analysis
320+
configuration().setIgnoreIncrementalAnalysis(true);
321+
319322
final File sourceCodeFile = file.getRawLocation().toFile();
320323
if (included && InternalRuleSetUtil.ruleSetsApplies(ruleSets, sourceCodeFile) && isFileInWorkingSet(file)
321324
&& languageVersion != null) {

net.sourceforge.pmd.eclipse.plugin/src/main/java/net/sourceforge/pmd/eclipse/runtime/writer/impl/AstWriterImpl.java

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import java.io.OutputStream;
88
import javax.xml.parsers.FactoryConfigurationError;
9+
import javax.xml.transform.OutputKeys;
910
import javax.xml.transform.Transformer;
1011
import javax.xml.transform.TransformerException;
1112
import javax.xml.transform.TransformerFactory;
@@ -26,20 +27,14 @@
2627
*
2728
*/
2829
class AstWriterImpl implements IAstWriter {
29-
/**
30-
* @see net.sourceforge.pmd.eclipse.runtime.writer.IAstWriter#write(java.io.Writer,
31-
* net.sourceforge.pmd.ast.ASTCompilationUnit)
32-
*/
30+
@Override
3331
public void write(OutputStream outputStream, ASTCompilationUnit compilationUnit) throws WriterException {
3432
try {
3533
Document doc = compilationUnit.getAsDocument();
3634
Transformer transformer = TransformerFactory.newInstance().newTransformer();
35+
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
3736
transformer.transform(new DOMSource(doc), new StreamResult(outputStream));
38-
} catch (DOMException e) {
39-
throw new WriterException(e);
40-
} catch (FactoryConfigurationError e) {
41-
throw new WriterException(e);
42-
} catch (TransformerException e) {
37+
} catch (DOMException | FactoryConfigurationError | TransformerException e) {
4338
throw new WriterException(e);
4439
}
4540
}

net.sourceforge.pmd.eclipse.plugin/src/main/java/net/sourceforge/pmd/eclipse/ui/actions/AbstractUIAction.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
*/
2222
public abstract class AbstractUIAction implements IObjectActionDelegate {
2323

24+
private ISelection selection;
2425
private IWorkbenchPart targetPart;
2526

2627
protected AbstractUIAction() {
@@ -59,7 +60,12 @@ protected IWorkbenchPartSite targetPartSite() {
5960
}
6061

6162
protected ISelection targetSelection() {
62-
return targetPartSite().getSelectionProvider().getSelection();
63+
return selection;
64+
}
65+
66+
@Override
67+
public void selectionChanged(IAction action, ISelection selection) {
68+
this.selection = selection;
6369
}
6470

6571
/**

0 commit comments

Comments
 (0)