How to suppress Java warnings for specific directories or files such as generated code
Asked Answered
E

13

118

I'm using a parser generator that creates somewhat ugly code. As a result my Eclipse project has several dozen warnings emanating from generated source files. I know I can use the @SuppressWarning annotation to suppress particular warnings in particular elements, but any annotations I add by hand will be lost when the parser generator runs again. Is there a way to configure Eclipse to suppress warnings for a particular file or directory?

Experimental answered 14/7, 2009 at 20:44 Comment(1)
Related to #230699Theatre
F
103

Starting with version 3.8 M6, Eclipse (to be exact: the JDT) has built-in functionality for this. It is configurable through a project's build path: Project properties > Java Build Path > Compiler > Source

enter image description here

Announced here: Eclipse 3.8 and 4.2 M6 - New and Noteworthy, called Selectively ignore errors/warnings from source folders. That's also where the screenshot is from. This is the new feature developed on the previously linked Bug 220928.

Flory answered 23/3, 2012 at 7:42 Comment(8)
I couldn't find how to switch "No" -> "Yes" ... it's "Toggle" button (and not edit or something else) ;-)Denigrate
@Betlista: Just double-click it. Or click Toggle button on the right.Piglet
@hheimbuerger: this solution works for source folders only. But what if I just have a folder in project containing some malformed XML files? I hate to see warnings about them :(Piglet
@Piglet The above feature/option comes from the JDT plugin, i.e. the Java support for Eclipse. (Remember that pretty much everything in Eclipse is a plugin, even the Java support is not baked in.) So you'd have to check back with the developer of the plugin you use to do the XML validation. IIRC, there are numerous, so you should probably open a new question specifically for the one you are using.Flory
+1. By the way, which OS did you use? Font rendering is quite strange.Kerstin
@SargeBorsch It is! But I think I took the screenshot from the Eclipse release notes and then annotated it, so I don't know what OS they use. Certainly doesn't look like that on my machine.Flory
@HDave FYI, the URL you posted didn't actually contain the bug ID.Flory
This solution fails if you make use of Maven M2E. Here's a link to the 3 year old bug report: bugs.eclipse.org/bugs/show_bug.cgi?id=388541Nosewheel
F
20

There is a ticket for this, Bug 220928, that has since been completed for Eclipse 3.8. Please see this answer for details.

If you're stuck with Eclipse 3.7 or lower: The user "Marc" commenting on that ticket created (or at least links to) a plugin called 'warningcleaner' in comment 35. I'm using that with a lot of success while waiting for this feature to be integrated into Eclipse.

It's really quite simple:

  1. Install plugin.
  2. Right-click project and select "Add/remove generated code nature".
  3. Open the project settings (right-click and select "properties").
  4. Open the tab 'Warning Cleaner'.
  5. Select the source folders you want to ignore the warnings from.

Warning Cleaner screenshot

Flory answered 25/1, 2011 at 15:52 Comment(11)
Unfortunately the link to the plugin gives a 403 nowSurgery
Damn, that sucks. I still have it, but I'd rather not upload it without explicit permission from the author, in particular as it specifies no license at all. Can you try to track down the original author and ask him to reupload it please? You could post on the bug for example, he is still listed as CC on it.Flory
It appears that progress is still being made (reading the comments on the bug) towards a core implementation. Make sure to update the question/answer to use specific version numbers if the feature is implemented. Otherwise, future users of Eclipse may be confused.Halvorson
@Chris Browne You're welcome to edit question and answer if you think it can be improved. :)Flory
I don't feel the question/answer can currently be improved, since the functionality has yet to exist, but if the functionality is ever added to eclipse then someone should edit this. Not necessarily me, but if I'm in the right place at the right time then of course I will do so.Halvorson
Does anyone have a current link to this plugin? I'd love to be able to use it!Fortieth
Attention: Eclipse now has a built-in solution for this, as you can see in the other answer from hheimbuerger. By the way, hheimbuerger, you should refactor this answer with updated info to make it the 'official'.Citronellal
@Citronellal I edited a link in, but mostly, you should just upvote the other answer so it appears over this one. :)Flory
github.com/mflament/eclipse-warning-cleaner/releases is the new location of this plugin.Featly
> "... is the new location of this plugin": not any more: 404 not found... :-(Harrar
@Harrar It's been more than 11 years now... I feel for you if you're still stuck on Eclipse 3.7. 😳 (Nevertheless, I hate it when GitHub projects are deleted!)Flory
K
18

I solved this by using the maven regexp replace plugin - it does not solve the cause, but heals the pain:

<plugin>
  <groupId>com.google.code.maven-replacer-plugin</groupId>
  <artifactId>maven-replacer-plugin</artifactId>
  <version>1.3.2</version>
  <executions>
<execution>
  <phase>prepare-package</phase>
  <goals>
    <goal>replace</goal>
  </goals>
</execution>
  </executions>
  <configuration>
<includes>
  <include>target/generated-sources/antlr/**/*.java</include>
</includes>

<regex>true</regex>
<regexFlags>
  <regexFlag>MULTILINE</regexFlag>
</regexFlags>

<replacements>
  <replacement>
    <token>^public class</token>
    <value>@SuppressWarnings("all") public class</value>
  </replacement>
</replacements>
  </configuration>
</plugin>

Note that I did not manage to get the ** notation to work, so you might have to specify path exactly.

See comment below for an improvement on how not to generate duplicate @SupressWarnings

Kastner answered 20/9, 2010 at 9:2 Comment(4)
As Maven was not mentioned, this does not necessarily answer the question. But it works great in my case, as I use Maven ;-)Surgery
The same thing can be done if you're using Ant instead of Maven, see my answer.Recliner
it seems that ANTLR 3.4 adds the annotation by itself, but I like the generality of the solution (not only ANTLR generates code). To still apply it to all generated sources, I use this pattern: ^(@SuppressWarnings\(.*?\)\s+)?public class. By including the annotation in the pattern, it isn't duplicated if it's already there.Sexology
This (more or less) worked for me -- I had to add ${basedir}/ before target in the <include> tag. Feels kinda janky, but since it only works on generated files, I'll take it!Sannyasi
B
7

I think the best you can do is enable project specific settings for displaying warnings.

Window -> Preferences -> Java -> Compiler -> Errors/Warnings

On the top of the form is a link for configuring project specific settings.

Ballonet answered 14/7, 2009 at 20:49 Comment(1)
That only allows to adjust errors/warnings/infos on a project level but not to exclude specific directories.Harrar
A
4

User @Jorn hinted at Ant code to do this. Here's what I have

<echo>Adding @SuppressWarnings("all") to ANTLR generated parser/lexer *.java</echo>
<echo> in ${project.build.directory}/generated-sources/antlr/</echo>
<replace dir="${project.build.directory}/generated-sources/antlr/" 
         summary="true" 
         includes="**/*.java" 
         token="public class" 
         value='@SuppressWarnings("all") public class' />

Note that Ant's <replace> does text replacement, not regular expression replacement, so it cannot use the ^ meta-character in the token to match beginning of line as the maven regexp replace plugin does.

I'm doing this at the same time that I run Antlr from maven-antrun-plugin in my Maven pom, because the ANTLR maven plugin did not play well with the Cobertura maven plugin.

(I realize this is not an answer to the original question, but I can't format Ant code in a comment/reply to another answer, only in an answer)

Aruwimi answered 9/5, 2011 at 19:5 Comment(0)
P
1

I don't think Eclipse inherently provides a way to do this at the directory level (but I'm not sure).

You could have the generated files go into a separate Java project, and control warnings for that specific project.

I generally prefer to place automatically-generated code in a separate project anyway.

Potman answered 14/7, 2009 at 20:49 Comment(0)
L
1

You can only suppress warnings at the project level. However, you can configure your problems tab to suppress warnings from files or packages. Go into the Configure Contents menu and work with the "On working set:" scope.

Lanita answered 14/7, 2009 at 20:51 Comment(4)
The Configure Contents menu doesn't make any sense to me.Experimental
You can't find it or you can't figure out where to navigate in it? I'm using Eclipse 3.4.1 (I think it a Ganymede install with PyDev added). It's located on the upper right hand corner of the Problems tab when you click on the little arrow icon to drop down the menu for that tab.Lanita
I can find it. I don't understand what changing the settings in that dialog would accomplish.Experimental
I can see how this could work, but then you'd have to use working sets, which isn't a generic solution. It adds to the problem because now you have to update your working set to see the right warnings.Supernational
H
1

This small python script "patches" the M2E-generated .classpath files and adds the required XML tag to all source folders starting with target/generated-sources. You can just run it from you project's root folder. Obviously you need to re-run it when the Eclipse project information is re-generated from M2E. And all at your own risk, obviously ;-)

#!/usr/bin/env python
from xml.dom.minidom import parse
import glob
import os

print('Reading .classpath files...')
for root, dirs, files in os.walk('.'):
    for name in files:
        if (name == '.classpath'):
            classpathFile = os.path.join(root, name)
            print('Patching file:' + classpathFile)
            classpathDOM = parse(classpathFile)
            classPathEntries = classpathDOM.getElementsByTagName('classpathentry')
            for classPathEntry in classPathEntries:
                if classPathEntry.attributes["path"].value.startswith('target/generated-sources'):
                    # ensure that the <attributes> tag exists
                    attributesNode = None;
                    for attributes in classPathEntry.childNodes:
                            if (attributes.nodeName == 'attributes'):
                                attributesNode = attributes

                    if (attributesNode == None):
                        attributesNode = classpathDOM.createElement('attributes')
                        classPathEntry.appendChild(attributesNode)

                    # search if the 'ignore_optional_problems' entry exists
                    hasBeenSet = 0
                    for node in attributesNode.childNodes:
                        if (node.nodeName == 'attribute' and node.getAttribute('name') == 'ignore_optional_problems'):
                            # it exists, make sure its value is true
                            node.setAttribute('value','true')
                            #print(node.getAttribute('name'))
                            hasBeenSet = 1

                    if (not(hasBeenSet)):
                        # it does not exist, add it
                        x = classpathDOM.createElement("attribute")
                        x.setAttribute('name','ignore_optional_problems')
                        x.setAttribute('value','true')
                        attributesNode.appendChild(x)

            try:
                f = open(classpathFile, "w") 
                classpathDOM.writexml(f)
                print('Writing file:' + classpathFile)
            finally:
                f.close()
print('Done.')
Hormonal answered 19/2, 2013 at 9:40 Comment(0)
R
0

I'm doing this to a few ANTLR grammars, which generate a Java parser using Ant. The Ant build script adds the @SuppressWarnings("all") to one Java file, and @Override to a few methods in another. I can look up how it's done exactly, if you're interested.

Recliner answered 14/7, 2009 at 21:46 Comment(3)
An interesting idea. Doesn't the @SuppressWarnings need to come just before the class declaration (i.e., it's not as easy as inserting it on the first line of the file)?Experimental
It does need to be placed there, but it's doable. I needed to dive deep into the ant documentation to find the right function tough, but I don't have a lot of experience with Ant.Recliner
See antlr.org/wiki/pages/viewpage.action?pageId=1865 which describes how to modify the ANTLR Java codegen template. However, it is not clear how to make that work when using the ANTLR plugin for Eclipse. I guess one is left with hacking the plugin jar or using one of the other workarounds listed above.Aruwimi
S
0

In the case of ANTLR 2, it is possible to suppress warnings in generated code by appenidng @SuppressWarnings before the class declaration in the grammar file, e.g.

{@SuppressWarnings("all")} class MyBaseParser extends Parser;
Slovenia answered 30/7, 2010 at 10:23 Comment(0)
M
0

This can be done by excluding certain directories from the build path (The following example is given using Eclipse 3.5)

[1] Bring up the Java Build Path

  • Click on the projectin Package Explorer
  • Right click, properties
  • Select Java Build Path

[2] Add directories to exclude

  • The Source tab should contain details of the project source folders
  • Expand the source folder and locate the 'Excluded:' property
  • Select 'Excluded:' and click Edit
  • Add folders into the Exclusion patterns using the Add/Add Multiple options
  • Click Finish, then ok for Eclipse to rebuild.
Mousetail answered 3/1, 2012 at 16:6 Comment(0)
S
0

It's been a while since I have released the warning-cleaner plugin, and now that I am using Eclipse 3.8, I have no need for it anymore. However, for those who still need this plugin, I have released it on github with the update site on bintray. If you are still using Eclipse 3.7 or before, this could be useful. Check this site for installation details.

Socialistic answered 21/4, 2014 at 12:44 Comment(0)
F
0

If the eclipse project is generated from gradle using Eclipse plugin's eclipse command the Selectively ignore errors/warnings from source folders option can be set by adding this on the top level of you build.gradle file:

eclipse.classpath.file {
    whenMerged { classpath ->
        classpath.entries.each { entry -> 
            if (entry.path.contains('build/generated/parser')) {
                entry.entryAttributes['ignore_optional_problems'] = true
            }
        }
    }
}

This assumes that generated sources are in build/generated/parser folder.

Fluoridation answered 5/6, 2020 at 19:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.