I was wondering if there is a general strategy that can be applied to show errors (or warnings etc.) in the validator.
I know there is the error function, that take arguments like:
message
source
feature
and others...
Is it possible to call this function in a generic way that works at least most of the time? I know that there are people that call the function like:
error("MyMessage", eObject.eContainer(), eObject.eContainingFeature(), ...), however, this puts the error in the wrong place most of the times. Isn't it possible to just add an Error to the eObject without caring about the features and stuff?
When I call it like this: error("MyMessage", eObject, eObject.eContainingFeature(), ...) I get an Exception, because the feature and the eObject does not match.
I just found the answer. You can set the feature to null.
So you can call the function like:
error("MyMessage", eObject, null, ...)
Related
There may be some related questions, but I think my situation is peculiar enough to justify a question on its own.
I'm working on a historically grown huge Java project (far over one million LOC, due to other reasons we're still bound to Java 6 at the moment), where reflection is used to display data in tables - reflection is not used for dynamically changing the displayed data, but just for using some kind of short cuts in the code. A simplified part of the code looks like this.
TableColumns taco = new TableColumns(Bean.class);
taco.add(new TableColumn("myFirstMember"));
taco.add(new TableColumn("mySecondMember"));
...
List<Bean> dataList = getDataFromDB(myFilterSettings);
taco.displayTable(dataList);
So the values of the table cells of each row are stored in an instance of Bean. The values for the first cell comes from calling itemOfDataList.getMyFirstMember() (so here comes the reflection part of the code). The rendering of the table cells is done depending on the return type of the itemOfDataList.getMyFirstMember().
This way, it's easy to add new columns to the table, getting them rendered in a standard way without caring about any details.
Problem of this approach: when the getter name changes, the compiler doesn't notice and there will be an exception at runtime in case Bean.getMyFirstMember() was renamed to Bean.getMyFirstMemberChanged().
While reflection is used to determine which getter is called, the needed info is in fact available at compile time, there are no variables used for the column info.
My goal: having a validator that will check at compile time whether the needed getter methods in the Bean class do exist.
Possible solultions:
modifying the code (using more specific infos, writing an adapter, using annotations or whatever that can be checked at compile time by the compiler), I explicitely don't want a solution of this kind, due to the huge code basis. I just need to guarantee that the reflection won't fail at runtime.
writing a custom validator: I guess this shouldn't be too complex, but I have no real idea how to start, we use eclipse as ide, so it should be possible to write such a custom validator - any hints for a good starting point?
The validator should show a warning in eclipse if the parameter in the TableColumn(parameter) isn't final (should be a literal or constant). The validator should show an error in eclipse if the TableColumn is added to TableColumns and the corresponding Bean.getParameter() doesn't exist.
as we use SonarQube for quality checking, we could also implement a custom rule checking if the methods do exist - not completely sure if such a custom rule is possible (probably yes)
maybe other solutions that will give a fast feedback within eclipse that some tables won't render correctly after some getter methods were renamed
What I'm asking for:
what will be easier in this situation: writing a custom validator for eclipse or writing a custom rule for SonarQube?
hints where to start either approach
hints for other solultions
Thanks for your help.
Some alternatives:
You could migrate to more modern Java for this pattern, it is a prime candidate for method references. Then, your IDE of choice can automatically take care of the problem when you refactor/rename. This can be done bit-by-bit as the opportunity/necessity arises.
You could write your own custom annotations:
Which you can probably get SonarQube to scan for
Which could allow you to take advantage of javax.validation.* goodies, so your code may look/feel more like 'standard' Java EE code.
Annotations can be covered by a processor during the build step, various build tools have ways to hook this up -- and the processor can do more advanced/costly introspection so you can push the validation to compile-time as opposed to run-time.
I am using IntelliJ IDEA 15, and I noticed that (by default) Eclipse offers a much more convenient auto-completion, when it comes to writing method calls, which require multiple parameters.
Eclipse automatically fills in default parameters and allows you to quickly navigate through them by pressing Tab:
However, IntelliJ IDEA does not handle it as conveniently and makes you write them manually:
Is there a way to make IntelliJ IDEA, handle method call auto-completion in a similar way to Eclipse's, and pre-write all the parameters for you, having you just press Tab (or another key) to navigate through them? If it is not possible in original IntelliJ, is there an add-on/plugin/external tool that will improve the intelligent code completion in such cases?
Note: I am not being lazy, it just gets quite annoying, having to manually complete each parameter and put a comma after each one, when code completion should do it for you.
IntelliJ doesn't do it and AFAIK there isn't a plugin for it.
There is no solution for you (unless you built a plugin yourself, but then you'd just have another job to maintain that plugin)
The alternative is to break the habit/need for it and use IntelliJ's Code Completion shortcuts:
Ctrl+P to view possible parameters for function.
Ctrl+Shift+Space to list the possible variables that could be entered as a parameter in the respective parameter position (based on type).
This also enters a comma if another parameter is required for the function.
Hardcoding numbers/strings as parameters to a custom function wouldn't be advisable as that negates the point of the parameters. It's better practice and more common to pass in a pre-defined variable; At which point Ctrl+Shift+Space is the easiest way for Code Completion.
This would also prevent you from closing quotations and adding commas.
Also note: IntelliSense is Microsoft's Intelligent Code Completion implementation which neither IntelliJ nor Eclipse uses.
As frant.hartm states in their answer:
Unfortunately the view of Intellij developers is that this feature would be too error prone. See this issue on youtrack.
They even state that people are welcome to make a plugin that does this.
The closest thing to this AFAIK is "method parameter completion", which allows you to auto complete parameters of current method as parameters of the inner method call at once (works for methods and constructors when calling super()).
Unfortunately the view of Intellij developers is that this feature would be too error prone. See this issue on youtrack.
IDEA doesn't fill the arguments automatically. You can use Ctrl+Shift+Space for auto-completion (completion is based on type, not name) or Ctrl+Alt+Space for suggestion. Or Ctrl+P to see what arguments are accepted.
Try
Ctrl + Space
for
Basic Code Completion
And like previously was written
Ctrl + Shift + Space
for
Type Code Completion
or try the second variant TWICE. More about Auto-Completing Code is in here
I have an Eclipse plugin which has the purpose of indexing and searching XML files for custom frameworks used by the application my team develops.
There is a toolbar with several buttons on it. Each button has its own command and each command is linked to a separate handler which brings up a search dialog.
The handlers differ only by which file type they search. Currently there are ten concrete handlers and one abstract. All of the functionality is handled in the abstract class, and the concrete classes only implement an abstract "get file type" method.
Ideally I would only have one handler. This means there would need to be a way to inject the enum into the base class directly.
I looked at command parameters, but this appears to be user-facing. I need something hard-coded where the command tells the handler "use this value." I don't care if this is a constructor argument or some hard-coded parameter in plugin.xml.
Thus far I have not been able to find a way to do this. Perhaps my Google-fu is weak, perhaps I am just not seeing it.
Is there a way to specify a hard-coded parameter to a handler constructor or to call a method to set a parameter after it is constructed but before it is invoked?
Command parameters are the right way to achieve that. What are the problems you face with that? Here is an example to use the parameters
So I'm writing a compiler in Java using ANTLR, and I'm a little puzzled by how it deals with errors.
The default behavior seems to be to print an error message and then attempt, by means of token insertion and such, to recover from the error and continue parsing. I like this in principle; it means that (in the best case) if the user has committed more than one syntax error, they'll get one message per error, but it'll mention all the errors instead of forcing them to recompile to discover the next one. The default error message is fine for my purposes. The trouble comes when it's done reading all the tokens.
I am, of course, using ANTLR's tree constructors to build abstract syntax trees. While it's nice for the parse to continue through syntax errors so the user can see all the errors, once it's done parsing I want to get an exception or some kind of indication that the input wasn't syntactically valid; that way I can stop the compilation and tell the user "sorry, fix your syntax errors and then try again". What I don't want is for it to spit out an incomplete AST based on what it thinks the user was trying to say, and continue to the next phase of compilation with no indication that anything went wrong (other than the error messages which went to the console and I can't see). Yet by default, it does exactly that.
The Definitive ANTLR Reference offers a technique to stop parsing as soon as a syntax error is detected: override the mismatch and recoverFromMismatchedSet methods to throw RecognitionExceptions, and add a #rulecatch action to do the same. This would seem to lose the benefit of recovering from parse errors, but more importantly, it only partially works. If a necessary token is missing (for instance, if a binary operator only has an expression on one side of it), it throws an exception just as expected, but if an extraneous token is added, ANTLR inserts the token that it thinks belongs there and continues on its merry way, producing an AST with no indication of a syntax error except a console message. (To make matters worse, the token it inserted was EOF, so the rest of the file didn't even get parsed.)
I'm sure I could fix this by, say, adding something like an isValid field to the parser and overriding methods and adding actions so that, at the end of the parse, it throws an exception if there were any errors. But is there a better way? I can't imagine that what I'm trying to do is unusual among ANTLR users.
... [O]nce it's done parsing I want to get an exception or some kind of indication that the input wasn't syntactically valid; that way I can stop the compilation...
You can call getNumberOfSyntaxErrors on both the lexer and the parser after parsing to determine if there was an error that was covertly accommodated by ANTLR. This doesn't tell you what those errors were, obviously, but I think these methods address the "once it's done parsing ... stop the compilation" part of your question.
The Definitive ANTLR Reference offers a technique to stop parsing as soon as a syntax error is detected: override the mismatch and recoverFromMismatchedSet methods to throw RecognitionExceptions, and add a #rulecatch action to do the same.
I don't think you mentioned which version of ANTLR you're using, but the documentation in the ANTLR v3.4 code for the method recoverFromMismatchedSet says it's "not currently used" and an Eclipse "global usage" scan found no callers. Neither here nor there to your main problem, but I wanted to mention it for the record. It may be the correct method to override for your version.
If a necessary token is missing ..., [the overridden code] throws an exception just as expected, but if an extraneous token is added, ANTLR inserts the token that it thinks belongs there and continues on its merry way...
Method recoverFromMismatchedToken tests for a recoverable missing and extraneous token by delegating to methods mismatchIsMissingToken and mismatchIsUnwantedToken respectively. If the appropriate method determines that an insertion or deletion will solve the problem, recoverFromMismatchedToken makes the appropriate correction. If it is determined that no operation solves the mismatched token problem, recoverFromMismatchedToken throws a MismatchedTokenException.
If a recovery operation takes place, reportError is called, which calls displayRecognitionError with the details.
This applies to ANTLR v3.4 and possibly earlier versions.
This gives you at least two options:
Override recoverFromMismatchedToken and handle errors at a fine-grained level. From here you can delegate the call to the super implementation, roll your own recovery code, or bail out with an exception. Whatever the case, your code will be called and thus will be aware that a mismatch error occurred, recoverable or otherwise. This option is probably equivalent to overriding recoverFromMismatchedSet.
Override displayRecognitionError and handle the errors at a course-grained level. Method reportError does some state juggling, so I wouldn't recommend overriding it unless the overriding implementation calls the super-implementation. Method displayRecognitionError appears to be one of the last calls in the recovered-token call chain, so it would be a reasonable place to determine whether or not to continue. I would prefer it had a name that indicated that it was a reasonable place for that, but oh well. Here is an answer that demonstrates this option.
I'm partial towards overriding displayRecognitionError because it provides the error message text easily enough and because I know it's going to be called only after a token recovery operation and required state juggling -- no need for my parser to figure out how to recover for itself. This coupled with getNumberOfSyntaxErrors appear to give you the options that you're looking for, assuming that you're working with a relevant version of ANTLR and that I fully understood your problem.
As title, I have an requirement to define set of error code. The error code might be an unique string. It will be supposed to locate where and when the exception threw out.Just like oracle error code 'ORA-xxxxxx', so do we have a simple way to generate it?It might be built up by classname, method name or.....I can collect stack trace information from where the error occurs.Therefore anyone can help me or give me any strategy about this?
I don't think there is any way to automatically generate this. You will have to sit down, write up the list of error codes and update all your error-handling code to work accordingly.
You may want to have a MyApplicationException class with getErrorCode() that handles consistent formatting and things like that, but figuring out which error code to use will be manual work.
I'd also argue that these "user-visible, well-defined error codes" do not replace the information you can get from a stacktrace (which a developer/support person would need to see).