Write Java Method Signature with Annotated paramaters with JDT - java

I am writing an eclipse plug-in which generates code. I am leveraging eclipse jdt to gen out classes, fields, and methods. One of the requirements I have is to generate methods with annotated paramaters...
public returnType foo(#someAnnotation int id)
{
.....
.....
}
Does anybody know how to write out the #someAnnotation using JDT? To write out normal parameters in JDT you could do something like the following
Signature.createTypeSignature("int", false)

Have you tried debugging the creation of a type signature with an annotation and inspect the parameters passed to createTypeSignature?

Yes I have tried this. The createTypeSignature() function does validation on the String that is passed to it. When it sees something like the following it throws an exception...
Signature.createTypeSignature("#PathParam(\"custId\") int");
Hope this clears it up, and thanks for the response. Let me know if you have any other ideas.

Related

The exception "NoSuchMethodError" appears in a multi module project of maven [duplicate]

On my current project, I've felt the need to create a sort of simulated callback system in Java using reflection. However, I'm having issues getting my reflection to actually function. The code at fault follows:
public Callback(Object parentObj, String methodName, Class<?>...parameters)
{
if(parentObj == null)
throw new IllegalArgumentException("parentObj cannot be null", new NullPointerException());
Class<?> clazz = parentObj.getClass();
// Trace debugging, see output
for(Method m : clazz.getDeclaredMethods())
if(m.getName().equals("myMethod")) System.out.println (m);
try { this.method = clazz.getMethod(methodName, parameters); }
catch(NoSuchMethodException nsme) { nsme.printStackTrace(); } // Exception caught
catch(SecurityException se) { se.printStackTrace(); }
this.parentObj = parentObj;
this.parameters = parameters;
}
When I construct the Callback object, I'm using syntax like this:
new Callback(this, "myMethod", boolean.class)
When I try to create my pseudo-callback, it hits the NoSuchMethodException catch block. I've included some trace debugging above to show the output of one of my methods failing. The output:
private void my.package.MyClass.myMethod(boolean)
java.lang.NoSuchMethodException: my.package.MyClass.myMethod(boolean)
at java.lang.Class.getMethod(Class.java:1605)
at my.package.other.Callback.<init>(Callback.java:63)
I couldn't figure the problem out, so I started hunting, to little avail. The best I could find was mention of versioning conflict between the compiled JAR and the runtime. However, MyJar.jar/META-INF/MANIFEST.MF contains Created-By: 1.6.0_02 (Sun Microsystems Inc.). My IDE is running C:\Program Files\Java\jdk1.6.0_02\bin\javac.exe to compile my project. I'm using C:\Program Files\Java\jdk1.6.0_02\bin\java.exe to run my JAR.
I'm at a loss why Class.getMethod is claiming the method doesn't exist, but Class.getMethods seems to have no problem finding it. Help? :(
Your method is private but getMethod() only returns public method.
You need to use getDeclaredMethod().
You need the parameter list to be absolutely correct for the method you want for the call to succeed.
I've found that tiny steps are important when doing reflection because the compiler doesn't help. Write a small snippet which actually invokes exactly the method you want to in this particular case, and then when that works, generalize it into the framework here. I would focus on the parameters passed.
The Javadoc for getMethod isn't explicit, but it looks like it might throw a NoSuchMethodException for methods that aren't public, and your method is private.
The versioning issue that can cause NoSuchMethodException isn't a difference between the compiler versions. It's a difference in the version of (in your case) MyClass at compile time versus runtime.
Since you're using reflection you issue might have nothing to do with versioning, though. Certainly that would not explain different behavior between getMethod and getDeclaredMethods, because you're running them against the same Class instance, hence a version difference isn't really possible.
Are you sure that the parameters match your actual method?

How to efficiently add method name to Java logging message without typing it in manually?

In my Java application, I would like the logs to reflect the calling method name in the message. So that a the following code:
void foo(){
logger.info("some message");
}
would result with log message:
2020:10:10T10:10:10 thread class #foo some message
I am using Logback and SLF4J, and I understand that I can use message template.
To my understanding, this uses reflection and traveling up the call stack, and is a performance hit my team has had issues with in the past.
As an alternative, I looked into AOP, such as AsepectJ. As far as I can find, the calling context is not supplied in any of the AOP libraries. A simple before/after/wrap option won't reveal the identity of the method in which the call is made.
I'm looking for a way to inject a logging aspect using annotations. Something like:
#LogMethodName
class enhancedLoggingClass{
void foo(){
logger.info("some message");
}
}
And in some code/DSL I would write something like:
filter Methods with LogMethodName attribute OR inherited attribute from class
for each method:
find call to Logger(String s, *)
change to Logger(method.getName() + s, *)
In the past, in a C# 2.0 project a colleague tried out writing "shadow" code in which we could do anything. But this bypassed the tooling and made debugging not work, etc. So that was ditched.
Any suggestion are welcome.

#NotNull not working as expected

I have a method like:
public String getParamValue(#NotNull String param) {
.......
.......
.......
}
Even after putting #NotNull in-front of the param, whenever i am calling getParamValue(null) it is not throwing NPE. It proceeds as normal, do i need to do something else or am i using it wrongly? Thanks.
I am using Java 7 and javax.validation.constraints.NotNull if it helps in any ways.
This annotation doesn't do anything by itself. It is just a mark for other tools, so they know the constraints. The tools that checks it are source code analyzers and validation tools.
This is not a garantee for notnull, its more like a promise. so you could do a preconditions check:
if (param == null) {
throw new PreconditionExc...
Hi this question has already been asked before.
To summarize you will need to do this:
MVC namespace configuration for annotations:
The JSR-303 spec JAR: validation-api-1.0.0.GA.jar (looks like you already have that)
An implementation of the spec, such as Hibernate Validation, which appears to be the most commonly used example: hibernate-validator-4.1.0.Final.jar
you could also use one of these
https://code.google.com/p/gwt-validation/ and
http://bval.apache.org/
In the bean to be validated, validation annotations, either from the spec JAR or from the implementation JAR (which you have already done)
In the handler you want to validate, annotate the object you want to validate with #Valid, and then include a BindingResult in the method signature to capture errors.
Annotations from javax.validation.constraints not working

Validation of method parameters

I have a RESTful web service. For implementation using JAX-RS (Jersey).
Have the following method:
public void foo (#PathParam ("name") String uuid) {
...
}
I need to do validation of input parameters. And if data invalid throw WebApplicationException.
I added my custom annotation CheckUuid (extends ):
public void foo (#PathParam ("name") #CheckUuid String uuid) {
...
}
Is it possible to do validation using annotations on a stage when the method chosen, but not yet called? For example using PreProcessInterceptor?
Java EE6 has some built in validation functionality.
http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html
I have not used it however, but I saw it brought up during Java One and it looks pretty cool.
I'm not sure at what point this would happen, but I think it might work out for you.
As a result, it was decided to use the standard pattern in the method validation. Because in Jersey do not have PreProcessInterceptor.

Webservice problem - methods can't take more than 1 parameter

I'm using IntelliJ IDEA 8 and Axis to set up a webservice that's deployed on Tomcat5.5. The generated wsdl looks like this: http://track.priskick.se/Tracker.wsdl
A method is declared as
public void storeImpressionReport(int siteId, int adId, int zoneId, int count,
int excludeCount) { ... }
and exposed in the webservice. Next, I build the client (also Java) using Axis, but as a runtime call to the method is made with the parameters 0,0,0,0,0, I get this:
Tried to invoke method public void com.xxxxx.xxxx.xxxx.xxxxx.storeImpressionReport(int,int,int,int,int) with arguments java.lang.Integer,null,null,null,null. The arguments do not match the signature.; nested exception is: java.lang.IllegalArgumentException
Reducing the number of parameters of the method to 1 makes it work, however this feels like a pretty silly limitation and strange behaviour. Please help me if you know what might be wrong here - why can't I expose methods and have them take more than one parameter?
=== UPDATE
I now tried generating the client java using wsdl generated from IntelliJ instead of calling the service with the ?wsdl option. This wsdl keeps the correct parameter names, maybe because the generator has access to the source. Now I get
No such operation 'siteId'
AxisFault
These are the relevant files:
http://track.priskick.se/Tracker/TrackerSoapBindingStub.java
http://track.priskick.se/Tracker/TrackerServiceTestCase.java
http://track.priskick.se/Tracker/Tracker_PortType.java
http://track.priskick.se/Tracker/TrackerService.java
http://track.priskick.se/Tracker/TrackerServiceLocator.java
the wsdl used for the client is found at
http://track.priskick.se/Tracker.wsdl
the service is found at
http://stage.klikki.com/services/Tracker
Cheers
Marcus Johansson
Oh the joy. I changed the service style to WRAPPED, and this seems to have solved the problem.

Categories

Resources