line breaks after Java annotations in Scala code - java

I have a code that compiles successfully:
import javax.ws.rs.Path
trait DescriptionHandler extends ServiceAwareHandler {
#Path("/descriptions")
def getDescriptionsRoute: Route = ...
}
and it would not compile if I add a line break after Path annotation like this:
import javax.ws.rs.Path
trait DescriptionHandler extends ServiceAwareHandler {
#Path("/descriptions")
def getDescriptionsRoute: Route = ...
}
In IntelliJ IDEA it look like javax.ws.rs.Path is absent in class path.
Compiler telling me this:
Error:(19, 1) expected start of definition
def getDescriptionsRoute: Route =
What's the problem with line breaks between Java annotations and Scala methods / fields? I tried to google the issue but didn't found anything useful.

In Scala Spec/Lexical syntax/1.2 Newline characters there is an explicit statement about this case:
A single new line token is accepted
...
after an annotation.
And when there is an empty line:
if two tokens are separated by at least one completely blank line (i.e a line which contains no printable characters), then two nl tokens are inserted.
Thus blank lines are not accepted between annotation and definition.

Related

Doxygen annotation/attribute are ignored

I use doxygen to generate xml which then i transform to a custom documentation.
Is there a possibility that doxygen includes the annotation of a field / class / function.
The annotation are ignored in both java and c#.
ex:
class User
{
[Required]
string UserName {get;set;}
}
the "Required" annotation is not parsed/displayed in doxygen.
What I would like to have in the xml / html output of doxygen is all the annotated Annotations of a property / field / class (in the ex. "[Required]").
EXTRACT_ALL=YES is useless in this case. Look at this answer, I think it is good idea:
Doxygen and add a value of an attribute to the output documentation
So you have to create filter (for example in phyton) which will be used by Doxygen to convert annotation to comment. Don’t forget to inform Doxygen about your filter: INPUT_FILTER = doxygenFilter.py
I have the same problem so I modified that example in this way:
#!/usr/bin/env python
import sys
import re
if (len(sys.argv) < 2):
print "No input file"
else:
f = open(sys.argv[1])
line = f.readline()
while line:
re1 = re.compile("\s*\[(.*)]\s*")
re1.search(line)
sys.stdout.write(re1.sub(r"/// <para>Annotation: [\1]</para>\n", line))
#sys.stdout.write(line)
line = f.readline()
f.close()
So code like
[AnyAnnotation()]
Will be converted to:
/// <param> Annotation [AnyAnnotation()] </param>`
So I got very nice result. Tag <param> is to avoid Doxygen put this annotation description to main description. Instead it will put it to remarks section.
I'm not sure what you're asking but I will say a few things that might help you.
Doxygen must be configured to produce documentation for code elements that have no Doxygen comments. In other words, you can tell Doxygen to produce documentation for all functions, variables, macros, etc even if they aren't documented in the code. Set EXTRACT_ALL=YES in your config file.
If you run DoxyWizard you will get a better feel for all of the available options and the effect of each option. DoxyWizard is the GUI front end to Doxygen.
And by the way, bravo for documenting your code!

Xtext - No viable alternative at input

i'm trying to create a grammar that join togheter a script language with the possibility to create method.
Grammar
grammar org.example.domainmodel.Domainmodel with org.eclipse.xtext.xbase.Xbase
generate domainmodel "http://www.example.org/domainmodel/Domainmodel"
import "http://www.eclipse.org/xtext/xbase/Xbase" as xbase
Model:
imports = XImportSection
methods += XMethodDeclaration*
body = XBlockScriptLanguage;
XMethodDeclaration:
"def" type=JvmTypeReference name=ValidID
'('(params+=FullJvmFormalParameter (',' params+=FullJvmFormalParameter)*)? ')'
body=XBlockExpression
;
XBlockScriptLanguage returns xbase::XExpression:
{xbase::XBlockExpression}
(expressions+=XExpressionOrVarDeclaration ';'?)*
;
At the moment i create the following JvmModelInferr, for defining the main method for scripting language.
JvmModelInferr
def dispatch void infer(Model model, IJvmDeclaredTypeAcceptor acceptor, boolean isPreIndexingPhase) {
acceptor.accept(
model.toClass("myclass")
).initializeLater [
members += model.toMethod("main", model.newTypeRef(Void::TYPE)) [
parameters += model.toParameter("args", model.newTypeRef(typeof(String)).addArrayTypeDimension)
setStatic(true)
body = model.body
]
]
}
When i tryed to use my grammar, i obtain the following error after that i wrote my method:
no viable alternative at input 'def'
The method mymethod() is undefined
The problem is related only with method declaration, without it myclass.java is created.
Moreover i obtain the "Warning 200" for a not clear grammar, why?
There are two fixes that appear necessary:
The imports section is not marked as optional. If it was intended to be optional, it should be declared as imports ?= XImportSection. Or, add necessary import statements to your JvmModelInferr example.
The dispatch keyword isn't defined in your grammar. As defined, a method should consist of def, followed by a Java type (the return type), and then the method's name (then the body, etc.). You could add `(dispatch ?= 'dispatch') if you're targeting Xtend and intend to support its multiple dispatch feature (or your own version of it).
HTH

Using Gradle to generate JavaDoc with newline characters in the "header"

UPDATE: Made a posting on the Gradle forum. Please star this issue so that it gets more attention http://gsfn.us/t/4jedo
I'm in the process of transitioning from a primarily Ant build environment into a Gradle one. One sticking point is injecting Google Analytics and Adsense code into the JavaDoc. This is done by putting java script code into the header or bottom panels. For an example of what I'm currently doing, look at this question CDATA.
The problem with Gradle is that it can't handle newline characters in the string which is to be inserted. If you filter out those characters you break the script. Here is a code sniplet:
task alljavadoc(type: Javadoc) {
source = javadocProjects.collect { project(it).sourceSets.main.allJava }
classpath = files(javadocProjects.collect { project(it).sourceSets.main.compileClasspath })
destinationDir = file("${buildDir}/docs/javadoc")
configure(options) {
header = "this is\na test which should fail"
}
}
The critical part is "header =". If you remove the '\n' character it will work just fine. Otherwise the call to javadoc, which Gradle makes, will fail with the following error:
Successfully started process 'command '/opt/jdk/jdk1.7.0_21/bin/javadoc''
javadoc: error - Illegal package name: ""
javadoc: warning - No source files for package a
javadoc: warning - No source files for package test
javadoc: warning - No source files for package which
javadoc: warning - No source files for package should
javadoc: warning - No source files for package fail
The actual java script that I wish to include is below. Note that I can't hack it by removing new line characters since that will break the script.
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- banner -->
<ins class="adsbygoogle"
style="display:inline-block;width:468px;height:60px"
data-ad-client="ca-pub-xxxxxxxxxxxxxxxxx"
data-ad-slot="xxxxxxxxx"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
As a sanity check I also passed in a string with new line characters directly to javadoc (manual) on the command line and it works just fine.
javadoc foo.java -header "This is a test
and so is this"
The output HTML:
<div class="aboutLanguage"><em>This is a test
and so is this</em></div>
</div>
I have an explanation, but i don't have a solution except for creating a new feature request in Gradle JIRA.
To generate a javadoc Gradle first generates the so-called argfile at build\tmp\javadocTaskName\javadoc.options that contains all individual options and than executes javadoc #full\path\to\build\tmp\javadocTaskName\javadoc.options command.
It is actually quite useful as you can debug the contents of that file by simply invoking javadoc #javadoc.options yourself from the command line.
It is possible to define multi-line values in the argfile by using the \ character at the end of each line inside the multi-line value.
The example header = "this is\na test which should fail" results in
-header 'this is
a test which should fail'
but we need to get
-header 'this is\
a test which should fail'
to tell javadoc that the value continues on the next line.
Now the problem is how to output that \ on each line.
The obvious attempt at header = "this is\\\na test which should fail" does not work, it will result in
-header 'this is\\
a test which should fail'
And even Groovy multi-line or slashy strings will not work and will result in similar double back slashes.
Because Gradle just replaces all single backslashes in the option values. The JavadocOptionFileWriterContext.writeValue(String) method is the culprit, the replaceAll("\\\\", "\\\\\\\\") line in particular (a regex that matches single backslash and replaces it with double backslash ).
This escaping is required for backslashes inside a line, but it should not escape a single backslash followed by the new line character. My regex-fu is not strong enough to write such a pattern, but it is surely possible.
Or even better, the escaping mechanism inside that method should replace newline characters with a single backslash followed by the newline to hide all this stuff and allow users to declare multi-line javadoc options without the need to think or even know that feature.
I would appreciate if somebody can create an issue in Gradle tracker as i can't do so from my current location. This sentence should be replaced with the link to the issue so that people with similar problem can vote and track its progress.
I tried to implement it in Gradle but I couldn't get it to work reliably on windows. If the options file has this:
-header 'this is\
a test which should fail'
It works nicely on linux/mac but fails on windows (tried on win7/java7 and some other windows+java6). I've tried with vanilla javadoc executable (without Gradle).
I'll get the fix into Gradle and it will work out of the box for linux/mac but not quite for windows. If you want to help out with windows support catch us at http://issues.gradle.org/browse/GRADLE-3099

TestRig in ANTLRworks: how to use own classes?

I'm trying to build a MT940 parser using antlr4. The grammar is simple but works for most cases.
Now I want to return my own classes. This works:
file returns [String myString]
:
Header940? record+ EOF
;
I think this is becasue String is in the default java packages.
I want this:
file returns [List<MT940Record> records]
:
Header940? record+ EOF
;
The TestRig complains (logically):
/tmp/TestRigTask-1392235543340/MT940_5aParser.java:50: error: cannot find symbol
public List<MT940Record> records;
^
symbol: class MT940Record
location: class FileContext
How can I set the CLASSPATH / lib directory in the TestRig in ANLTRWorks?
In ANTLRWorks, you can't. You can add an issue for this on the issue tracker:
https://github.com/sharwell/antlrworks2/issues
Note that ANTLR 4 was designed so you no longer need to use user-defined arguments and/or return values in your grammar. Instead of returning a List<MT940Record> like you described above, you should use a listener or visitor after the parse is complete to compute the necessary result.

Java, cannot find symbol : method methodName(org.bla.blabla.myClass)

I'm using Lucene APIs, and I get the following error on this line of my code:
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Fieldable;
...
Document _document = new Document();
_document.add(new Field("type", document.getType()));
Error:
CollectionIndexer.java:34: cannot find symbol
symbol : method add(org.apache.lucene.document.Field)
location: class CollectionIndexer.Document
_document.add(new Field("type", document.getType()));
This is the documentation about the method:
http://lucene.apache.org/java/3_0_3/api/all/org/apache/lucene/document/Document.html#add(org.apache.lucene.document.Fieldable)
thanks
Update: javac -cp commons-digester-2.1/commons-digester-2.1.jar:lucene-core-3.0.3.jar myApp.java
When I'm stumped over this type of error, it is usually due to the fact that I've two definitions of InterfaceName, and accidentally imported the wrong one in one or more places.
(Happens for instance when I accidentally choose java.awt.List instead of java.util.List when auto-importing missing classes.)
Make sure that ...
symbol : method methodName(org.bla.blabla.myClass)
\____________________/
... this part ...
... matches the expected package / class.
The problem comes from the fact that your document.getType() method returns a String and there
is no constructor in the Field class that matches your call.
See http://lucene.apache.org/java/3_0_3/api/all/org/apache/lucene/document/Field.html.
If I test your code in my environment Eclipse says:
The constructor Field(String, String) is undefined
Maybe you could do as the following:
Document _document = new Document();
_document.add(new Field("type", document.getType().getBytes(), Store.YES);
// Or document.add(new Field("type", document.getType().getBytes(), Store.NO);
UPDATE after source code submission --------------------
The problem comes from the fact that in your class you have an inner-class called Document. There is a name conflict between your Document class and the Lucene's one. When you instanciate your document with the line Document _document = new Document(); you're actually instanciating YOUR Document class. That's why the compiler cannot find the add method.
Multiple solution:
a. Instanciate the Document prefixing it with the Lucene package name
org.apache.lucene.document.Document _document = new org.apache.lucene.document.Document();
b. Rename your inner class so that you don't have any name conflict.
Updated based on updates to question:
Make sure your curly braces around this line up and that there is not something else causing an issue.
Reduce the code down just to as few lines as possible to eliminate any other items that could be throughing the compiler off.
Compile without the commons-digester-2.1 if you can, to eliminate possible conflicts.
Break the line up so the a Field object is created on a separate line than adding the field to the document so that you can confirm there is no problem with your constructor call.

Categories